插入算法
循環數組,以指針數據爲基值 並且記錄,,通過和左側(右側)的循環比較,當比較值大於(小於)基值時
將大的值至後,指針繼續移動,比較,置換。直到遇到小於基值,或者到數組邊界時截止,並且置換至首位。
結束一次內循環,這是外循環的指針左側的是有序。
class Sort{
private long[] a;
private int nElement;
public Sort(long[] array){
this.a = array;
}
public static void main(String[] args) {
long[] array = new long[]{5,3,1,7,9,2,0};
Sort b = new Sort(array);
b.insertSort();
System.out.println(b);
}
public void insertSort(){
int out ,in;
int step = 0;
for(out = 0; out < a.length; out++){
long temp = a[out];//記錄外層循環時當前的基值
in = out; //比較位置已外層循環指針的位置開始,指針左側已有序。
while(in > 0 && a[in-1] > temp){
//當沒有到數組邊界 並且前一個值大於基值時 置換,並且將內循環指針前移,繼續比較
//前一個值,直到條件不滿足時跳出
a[in] = a[in-1];
--in;
step++;
}
// 將外層的基值至於排序中正確的位置
a[in] = temp;
}
System.out.println(step);
}
public String toString(){
StringBuilder b = new StringBuilder();
for(long l : a){
b.append(l);
b.append(",");
}
return b.toString();
}
}
例:
{5,3,1,7,9,2,0}
循環,3 < 5 將大值像後置換。並且指針前移
5,5,1,7,9,2,0,
已到數組邊界,將基值至於當前內循環指針位置。
3,5,1,7,9,2,0,
3,5,5,7,9,2,0,
3,3,5,7,9,2,0,
1,3,5,7,9,2,0,
1,3,5,7,9,9,0,
1,3,5,7,7,9,0,
1,3,5,5,7,9,0,
1,3,3,5,7,9,0,
1,2,3,5,7,9,0,