思想:將一個數組分成兩組,左邊那組始終有序,每次取右邊那組插入到左邊適當的位置,保證左邊有序,當右邊沒有需要插入的數據的時候,整個數組是有序的。插入排序是穩定排序。
注:此圖引用自https://www.cnblogs.com/chengxiao/p/6103002.html 文章,如有侵權請聯系我刪除
@Test
public void test() {
int[] array={4,2,7,3,5,4,0,45,16,36};
for(int i=1;i<array.length;i++){ //默認第零個是有序的
for(int j=i;j>0;j--){ //每次從右邊組增加一個數,與左邊數據判斷,交換位置(左邊數據進行排序)
if(array[j]<array[j-1]){
int temp=array[j];
array[j]=array[j-1];
array[j-1]=temp;
}
}
}
for(int n=0;n<array.length;n++){
System.out.println(array[n]);
}
}