forked from Hithomelabs/Princeton1
Reviewed-on: Hithomelabs/Princeton1#17 Reviewed-by: kruti <krutis0201@gmail.com> Co-authored-by: hitanshu310 <hitanshu98@gmail.com> Co-committed-by: hitanshu310 <hitanshu98@gmail.com>
48 lines
1.3 KiB
Java
48 lines
1.3 KiB
Java
package com.hithomelabs.princeton1.module5;
|
|
|
|
|
|
import java.util.Comparator;
|
|
|
|
public class Selection<E> implements MeasurableSort<E>, MeasurableHelper {
|
|
|
|
/*
|
|
* * Selection sort "selects" the smallest element and swaps it with arr[0] of the array
|
|
* * Then proceeds to do the same swapping arr[i] with arr[i:arr.length-1]
|
|
*/
|
|
public void sort(E[] arr){
|
|
coreSortLogic(arr, null, null);
|
|
}
|
|
|
|
private void coreSortLogic(E[] arr, Comparator<E> cmp, SortingMetaData metaData){
|
|
if (arr == null) return;
|
|
Comparable<E>[] arr1 = (Comparable<E>[]) arr;
|
|
for(int i = 0; i < arr1.length - 1; i++){
|
|
int minIndex = i;
|
|
for(int j = i+1; j < arr.length; j ++){
|
|
if (MeasurableHelper.less(arr[j], arr[minIndex], cmp, metaData)) minIndex = j;
|
|
}
|
|
MeasurableHelper.exch(arr, i, minIndex, metaData);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void sort(E[] arr, Comparator<E> cmp, SortingMetaData metaData) {
|
|
if (metaData != null)
|
|
metaData.startTime();
|
|
coreSortLogic(arr, cmp, metaData);
|
|
if (metaData != null)
|
|
metaData.endTime();
|
|
}
|
|
|
|
@Override
|
|
public void sort(E[] arr, Comparator<E> cmp) {
|
|
coreSortLogic(arr, cmp, null);
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return "Selection Sort";
|
|
}
|
|
}
|
|
|