import edu.princeton.cs.algs4.StdIn;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Comparator;
/**
* @author LFool
* @create 2020-07-24 16:39
*/
@SuppressWarnings({"rawtypes"})
public class Insertion {
/**
* 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 = 1; i < n; i++) {
for (int j = i; j > 0 && SortUtil.less(arr[j], arr[j - 1]); j--) {
SortUtil.exch(arr, j, j - 1);
}
assert SortUtil.isSorted(arr, 0, i);
}
assert SortUtil.isSorted(arr);
}
/**
* Rearranges the subarray(a[lo...hi]) in ascending order, using the natural order
* @param arr the array to be sorted
* @param lo left endpoint (inclusive)
* @param hi right endpoint (inclusive)
*/
public static void sort(Comparable[] arr, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++) {
for (int j = i; j > lo && SortUtil.less(arr[j], arr[j - 1]); j--) {
SortUtil.exch(arr, j, j - 1);
}
assert SortUtil.isSorted(arr, lo, i);
}
assert SortUtil.isSorted(arr);
}
/**
* 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 = 1; i < n; i++) {
for (int j = i; j > 0 && SortUtil.less(comparator, arr[j], arr[j - 1]); j--) {
SortUtil.exch(arr, j, j - 1);
}
assert SortUtil.isSorted(arr, comparator, 0, i);
}
assert SortUtil.isSorted(arr, comparator);
}
/**
* Rearranges the subarray(a[lo...hi]) in ascending order, using the natural order
* @param arr the array to be sorted
* @param comparator a comparator specifying the order
* @param lo left endpoint (inclusive)
* @param hi right endpoint (inclusive)
*/
public static void sort(Object[] arr, Comparator comparator, int lo, int hi) {
for (int i = lo; i <= hi; i++) {
for (int j = i; j > lo && SortUtil.less(comparator, arr[j], arr[j - 1]); j--) {
SortUtil.exch(arr, j, j - 1);
}
assert SortUtil.isSorted(arr, comparator, lo, i);
}
assert SortUtil.isSorted(arr, comparator, lo, hi);
}
public static void main(String[] args) throws FileNotFoundException {
FileInputStream input = new FileInputStream("src/main/resources/" + "tiny.txt");
System.setIn(input);
String[] arr = StdIn.readAllStrings();
Insertion.sort(arr, (Comparator<String>) (o1, o2) -> Character.compare(o2.charAt(0), o1.charAt(0)));
SortUtil.show(arr);
}
}