package suanfa;
import com.algs4.stdlib.StdOut;
/**
* Created by evan on 16/11/1.
* name 插入排序
*/
public class InsertSorting {
public static void main(String[] args){
Integer[] cpr = {121,3,1,22,44,12,5,6,23,664,22,34};
sort(cpr);
for (Integer value:cpr) {
StdOut.println(value);
}
}
public static void sort(Comparable[] cprList){
int N = cprList.length;
for (int i = 1;i < N;i++){
for(int j = i;j>=1 && less(cprList[j],cprList[j-1]);j--){
exch(cprList,j,j-1);
}
}
}
public static void exch(Comparable[] a,int b,int c){
Comparable t = a[b];
a[b] = a[c];
a[c] = t;
return;
}
public static Boolean less(Comparable a, Comparable b){
return a.compareTo(b) < 0;
}
}
在一个有序的数列中插入一个数,将数从右到左对比知道走到合适的位置
永远维护一个有序的数组,每次“插入”一个新的数是都要整理数组保持数组有序