https://en.wikipedia.org/wiki/Insertion_sort
loop1:
4,6,1,3,7 -> 4,6,1,3,7
loop2:
4,6,1,3,7 -> 4,1,6,3,7
4,1,6,3,7 -> 1,4,6,3,7
loop3:
1,4,6,3,7 -> 1,4,3,6,7
1,4,3,6,7 -> 1,3,4,6,7
1,3,4,6,7 -> 1,3,4,6,7
loop4:
1,3,4,6,7 -> 1,3,4,6,7
package sorting; import java.util.Arrays; import org.junit.Test; public class InsertionSorting { int[] items = { 4, 6, 1, 3, 7}; int step = 0; // ① 相邻 // ② 差一步 // ③ n个数可产生 n-1 对 // ④ 前面已经是排好序了,异类找到位置不动的时候,这一组就排好了 @Test public void sort() { for (int i = 1; i < items.length; i++) { for (int j = i; j > 0; j--) { step++; if (items[j - 1] > items[j]) { swap(j - 1, j); } else { break; } } } System.out.println(step + ":" + Arrays.toString(items)); } public void swap(int i, int j) { int backup = items[i]; items[i] = items[j]; items[j] = backup; } }