一、基本思路
将数组的划分为已排序序列和为排序序列,每次挑选为排序序列的第一个,插入已排序序列中(实际操作起来是逐个交换)
二、例子
我们以{3,5,7,9,8,6,2,1,4,0}数组的排序为例子,将[0,0]作为已排序区间,[1,9]作为未排序区间,用 | 分隔,初始化 i 为0,如下
|
3 | 5 | 7 | 9 | 8 | 6 | 2 | 1 | 4 | 0 |
第一趟:将 i 位置上的3插入到前面的区间,由于i为0,所以不作插入
|
3 | 5 | 7 | 9 | 8 | 6 | 2 | 1 | 4 | 0 |
第二趟:将 i 位置上的5插入到前面的区间,由于5>3,不作交换
|
3 | 5 | 7 | 9 | 8 | 6 | 2 | 1 | 4 | 0 |
......
第五趟:
|
3 | 5 | 7 | 9 | 8 | 6 | 2 | 1 | 4 | 0 |
此时8<9,会插入到9前面(实为与9交换位置),如下
|
3 | 5 | 7 | 8 | 9 | 6 | 2 | 1 | 4 | 0 |
......
经过10趟之后,完成排序
三、代码实现
public class InsertionSort {
public static void main(String[] args) {
int [] a=new int[]{3,5,7,9,8,6,2,1,4,0};
InsertionSort insertionSort=new InsertionSort();
insertionSort.insertionSort(a);
for(int item:a){
System.out.print(item+" ");
}
}
private void insertionSort(int [] a){
for(int i=0;i<a.length;i++){
for(int j=i;j>0;j--){
if(a[j]<a[j-1]){
int temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
}
}
四、复杂度
最好的情况,即当数组本来就是正序的情况下,只需比较n-1次,无需插入,所以为O(n)
最差和平均的情况都是O(n²)