InsertionSort { public static <T> T[] insertionSort(T[] array, Comparator<T> comparator) { for (int outer = 1; outer < array.length; outer++) { T item = array[outer]; int inner; for (inner = outer - 1; inner >= 0 && comparator.compare(array[inner], item) > 0; inner--) { array[inner + 1] = array[inner]; } array[inner + 1] = item; } return array; }  static T[] insertionSort(T[] array, Comparator<T> comparator);  }
@Test public void ascendingOrderSort() { Integer[] array = { 5, 4, 3, 2, 1 }; Integer[] sorted = InsertionSort.insertionSort(array, ascOrderComparator); assertArrayEquals("Failure => Array returned is not sorted.", sorted, new Integer[] { 1, 2, 3, 4, 5 }); }
@Test public void descendingOrderSort() { Integer[] array = { 1, 2, 3, 4, 5 }; Integer[] sorted = InsertionSort.insertionSort(array, descOrderComparator); assertArrayEquals("Failure => Array returned is not sorted.", sorted, new Integer[] { 5, 4, 3, 2, 1 }); }
@Test public void randomOrderSort() { Integer[] array = { 5, 1, 3, 2, 4 }; Integer[] sorted = InsertionSort.insertionSort(array, ascOrderComparator); assertArrayEquals("Failure => Array returned is not sorted.", sorted, new Integer[] { 1, 2, 3, 4, 5 }); }