将一个记录插入到已排序好的有序表中,从而得到一个新,记录数增1的有序表。即:先将序列的第1个记录看成是一个有序的子序列,然后从第2个记录逐个进行插入,直至整个序列有序为止。
要点:设立哨兵,作为临时存储和判断数组边界之用。
package com.whut.chenl.sort;
public class InsertSort {
public int[] insertSort(int[] array) {
for (int i = 0; i < array.length; i++) {
int currentValue = array[i];
int position = i;
for (int j = i-1; j >=0; j--) {
if (currentValue < array[j]) {
array[j+1] = array[j];
position--;
}else {
break;
}
}
array[position] = currentValue;
}
return array;
}
public void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.print("\n");
}
public static void main(String[] args) {
InsertSort sort = new InsertSort();
int[] array = new int[]{1,5,4,7,2,3};
sort.printArray(array);
sort.printArray(sort.insertSort(array));
}
}