public class InsertSort{ public static void main(String[] args) { int[] array = {34,8,64,51,32,21}; int[] a = insertionSort(array); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } public static int[] insertionSort(int[] array){ for (int i = 1; i < array.length; i++) { int tmp = array[i]; for (int j = i; j>0 && tmp <array[j-1];j--){ array[j] = array[j-1]; array[j-1] = tmp; } } return array; } }
當前元素tmp以前是已經排好序,那麼將當前元素和前面元素一個一個地去比較,若是但錢元素更小,說明該元素應該放到前面,也就是說須要交換這兩個元素的位置。而後循環執行,直到tmp元素的值比前面的元素要大。這時候,前面的元素就是有序的了。java
output:spa
8 21 32 34 51 64