public class InsertSort {
/**
* 直接插入排序算法
* 將一個記錄插入到已經排序好的有序表中
* @param args
*/
public static void main(String[] args){
int num[] = {44,1,3,5,2,8,4,9,7,6,21,11,2,99};
int temp,j;
for(int i=1; i<num.length; i++){
temp = num[i]; //設置爲哨兵
for(int n=0;n<num.length;n++){
System.out.print(num[n]+" ");
}
for(j=i-1;j>=0&&temp<num[j];j--){
num[j+1] = num[j];
}
num[j+1] = temp;
System.out.println("");
}
for(int n=0;n<num.length;n++){
System.out.print(num[n]+" ");
}
}
}
排序結果:
44 1 3 5 2 8 4 9 7 6 21 11 2 99
1 44 3 5 2 8 4 9 7 6 21 11 2 99
1 3 44 5 2 8 4 9 7 6 21 11 2 99
1 3 5 44 2 8 4 9 7 6 21 11 2 99
1 2 3 5 44 8 4 9 7 6 21 11 2 99
1 2 3 5 8 44 4 9 7 6 21 11 2 99
1 2 3 4 5 8 44 9 7 6 21 11 2 99
1 2 3 4 5 8 9 44 7 6 21 11 2 99
1 2 3 4 5 7 8 9 44 6 21 11 2 99
1 2 3 4 5 6 7 8 9 44 21 11 2 99
1 2 3 4 5 6 7 8 9 21 44 11 2 99
1 2 3 4 5 6 7 8 9 11 21 44 2 99
1 2 2 3 4 5 6 7 8 9 11 21 44 99
1 2 2 3 4 5 6 7 8 9 11 21 44 99