publicvoidinsertSort(T[] arr, Comparator<T> comparator){ for (int i = 1; i < arr.length; i++) { T temp = arr[i]; int j = i; for (; j > 0 && comparator.compare(arr[j - 1], temp) > 0; ) { arr[j] = arr[j - 1]; j--; } if (j != i) { arr[j] = temp; } } }
客户端的调用
1 2 3 4 5 6 7
publicstaticvoidmain(String[] args){ test<Cat> cattest = new test<Cat>(); Cat[] cat = {new Cat(2, "a"), new Cat(3, "d"), new Cat(4, "b"), new Cat(6, "a"), new Cat(3, "c")}; cattest.insertSort(cat, new CatSort()); System.out.println(Arrays.toString(cat));