1.排序思想:初始假设一个数组的第一个元素自成一个 有序序列,其余元素为无序序列,然后依次将无序序列的元素插入有序序列的适当位置中,直到最后一个记录插入为止。
2.代码实现:
import java.util.Arrays;
public class InsertSort {
public static void insertSort(int[] array,int n){
int i,j;
int x;//待插入有序序列元素
//i从第二个元素开始比较
for(i=1;i<n;i++){
x=array[i];
//j从有序序列的最后一个元素开始遍历
for(j=i-1;j>-1 && array[j]>x;array[j+1]=array[j],j--) ;
//for循环出来的j的下一个位置就是元素适合插入的位置
array[j+1]=x;
}
}
public static void main(String[] args){
int []array={4,7,3,2,8,6,9,5};
insertSort(array,array.length);
System.out.println(Arrays.toString(array));
}
}
3.时间复杂度:O(n^2)
4.空间复杂度:O(1)
5.稳定的排序算法
6.大部分元素有序时用效率比较高