import edu.princeton.cs.algs4.StdIn;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Comparator;
/**
* @author LFool
* @create 2020-07-24 01:04
*/
@SuppressWarnings({"rawtypes"})
public class Selection {
/**
* Rearranges the array in ascending order, using the natural order
* @param arr the array to be sorted
*/
public static void sort(Comparable[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int min = i;
for (int j = i; j < n; j++) {
if (SortUtil.less(arr[j], arr[min])) {
min = j;
}
}
SortUtil.exch(arr, i, min);
if (!SortUtil.isSorted(arr, 0, i)) {
throw new AssertionError();
}
}
if (!SortUtil.isSorted(arr)) {
throw new AssertionError();
}
}
/**
* Rearranges the array in ascending order, using a comparator
* @param arr the array
* @param comparator a comparator specifying the order
*/
public static void sort(Object[] arr, Comparator comparator) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int min = i;
for (int j = i; j < n; j++) {
if (SortUtil.less(comparator, arr[j], arr[min])) {
min = j;
}
}
SortUtil.exch(arr, i, min);
if (!SortUtil.isSorted(arr, comparator, 0, i)) {
throw new AssertionError();
}
}
if (!SortUtil.isSorted(arr, comparator)) {
throw new AssertionError();
}
}
/**
* Reads in a sequence of strings from standard input; selection sorts them;
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
FileInputStream input = new FileInputStream("src/main/resources/" + "tiny.txt");
System.setIn(input);
String[] arr = StdIn.readAllStrings();
Selection.sort(arr);
SortUtil.show(arr);
}
}