排序——插入排序(找坑)
假设前边部分已经排序,
取出下一个元素,将其与前边的元素依次比较(找坑),
找到合适的位置(在已排序部分),插入进去,
然后继续进行下一次比较,直到结束。
public class InsertSort {
public void insertSort(Integer[] arrays){
if(arrays.length == 0 || arrays == null) return;
int len = arrays.length;
int j = 0;
for(int i = 1; i < len; i++){
int temp = arrays[i];
for(j = i - 1; j >= 0; j--){
if(temp > arrays[j]) break;
arrays[j + 1] = arrays[j];
}
arrays[j + 1] = temp;
}
}
}
4 2 1 6 3 6 0 -5 1 1
2 4 1 6 3 6 0 -5 1 1
1 2 4 6 3 6 0 -5 1 1
1 2 4 6 3 6 0 -5 1 1
1 2 3 4 6 6 0 -5 1 1
1 2 3 4 6 6 0 -5 1 1
0 1 2 3 4 6 6 -5 1 1
-5 0 1 2 3 4 6 6 1 1
-5 0 1 1 2 3 4 6 6 1
-5 0 1 1 1 2 3 4 6 6
-5 0 1 1 1 2 3 4 6 6

浙公网安备 33010602011771号