InsertionSort { public int[] insertionSort(int[] unSort) { for (int j = 1; j < unSort.length; j++) { int key = unSort[j]; int i = j - 1; while (i >= 0 && unSort[i] > key) { unSort[i + 1] = unSort[i]; i--; } unSort[i + 1] = key; } return unSort; }  int[] insertionSort(int[] unSort);  }
@Test public void testInsertionSort() { StringBuilder strBuilder; { int[] unSort = {3, 2, 1}; int[] sort = insertionSort.insertionSort(unSort); strBuilder = new StringBuilder(); for (int i : sort) strBuilder.append(i); assertEquals("123", strBuilder.toString()); } { int[] unSort = {1, 1, 1}; int[] sort = insertionSort.insertionSort(unSort); strBuilder = new StringBuilder(); for (int i : sort) strBuilder.append(i); assertEquals("111", strBuilder.toString()); } { int[] unSort = {1, 2, 3}; int[] sort = insertionSort.insertionSort(unSort); strBuilder = new StringBuilder(); for (int i : sort) strBuilder.append(i); assertEquals("123", strBuilder.toString()); } }
@Test public void pressureTest() { final int ARRAY_SIZE = 1_0000; int[] sorted = new int[ARRAY_SIZE]; int[] reversed = new int[ARRAY_SIZE]; for (int i = 0; i < ARRAY_SIZE; i++) reversed[ARRAY_SIZE - i - 1] = sorted[i] = i; long begin; long end; { begin = System.currentTimeMillis(); insertionSort.insertionSort(sorted); end = System.currentTimeMillis(); _log.debug("Max: " + sorted[ARRAY_SIZE - 1] + ", and finished in " + (end - begin) + " millisecond"); } { begin = System.currentTimeMillis(); insertionSort.insertionSort(reversed); end = System.currentTimeMillis(); _log.debug("Max: " + sorted[ARRAY_SIZE - 1] + ", and finished in " + (end - begin) + " millisecond"); } }