插入排序:
public class insertSort {
public static void insert(int[] array) {
for(int i = 1; i < array.length; i++) {
int j = i;
while(j > 0 && array[j] < array[j-1]) {
int tt = array[j];
array[j] =array[j-1];
array[j-1] = tt;
j--;
}
}
}
public static void main(String[] args) {
int[] array = {3,2,1,0,5,6,5,4};
insert(array);
for(int a = 0; a < array.length; a++) {
System.out.print(array[a]);
}
}
}
过程如下:
初始数组:3,2,1,0,5,6,5,4
第一次排序:2, 3, 1, 0, 5, 6, 5, 4
第二次排序:1, 2, 3, 0, 5, 6, 5, 4
第三次排序:0, 1, 2, 3, 5, 6, 5, 4
第四次排序:0, 1, 2, 3, 5, 6, 5, 4
第五次排序:0, 1, 2, 3, 5, 6, 5, 4
第六次排序:0, 1, 2, 3, 5, 5, 6, 4
第七次排序:0, 1, 2, 3, 4, 5, 5, 6