插入排序是从数组的第二个数开始,也就是下标为1的地方。
插入排序将选取的值与前一个数进行比较:如果比前一个数大,则保持不变;如果比前一个数小,就将前一个数换到该位置,再与前二个数进行比较,同理如果比前两个数小,就将前二数换到前一个数位置,直到比前面的数大为止。
通过不断的对比排序,完成插入排序。
public class TestInsert1 {
public static void getInsertSort(int[] a){
if (a == null || a.length == 0){
System.out.println("该数组不存在或没有值");
}
int n = a.length;
int temp;
int j;
for (int i = 1; i < n; i++){
temp = a[i];
for (j = i-1; j >= 0 && a[j] > temp; j--){
a[j+1] = a[j];
}
a[j+1] = temp;
}
}
public static void main(String[] args) {
int[] a = {9,2,3,23,4,54,4};
getInsertSort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}