/**
* 直接插入排序
* @author sikaijian
*/
public class DirectInsertSort {
public static void sort(int[] data){
int pCurrent = 1; // 认定第0个数是有序的,从第1个数开始插入排序
int n = data.length;
while(pCurrent<n){
int front = pCurrent-1;
int key = data[pCurrent];
// 当前要插入的数和左边的有序队列比较(从右往左比较,比较一次移动一次)
while(front>-1 && key<data[front]){
data[front+1] = data[front];
front--;
}
data[front+1] = key;
pCurrent++;
}
}
/**
* 测试代码
* @param args
*/
public static void main(String[] args) {
int[] data = new int[] { 49, 23, 65, 13, 38, 96, 12, 33, 88, 123, 22,
11, 9, 55, 111, 0 };
for (int t : data) {
System.out.print(t);
System.out.print(" ");
}
System.out.println();
System.out.println("------------------------------");
DirectInsertSort.sort(data);
for (int t : data) {
System.out.print(t);
System.out.print(" ");
}
}
}