一:什么是插入排序
为了给要插入的元素腾出空间,我们需要将其余所有元素在插入之前都向右移动一位,当前索引左边的所有元素都是有序的,但最终位置不确定,为了给最小的元素腾出空间,元素可能随时被移动。
二:排序的实现
public class InsertSort { public static void main(String args[]){ int a[] = {10,23,5,2,112,34,22,99,0,45,1}; sort(a); show(a); } private static void sort(int[] a) { for(int i=1;i<a.length;i++){ for(int j=i;j>0 && less(a,j-1,j);j--){ exchange(a,j,j-1); } } } private static void exchange(int[] a, int m, int n) { int temp = a[n]; a[n] = a[m]; a[m] = temp; } private static boolean less(int[] a, int m, int n) { if(a[m] >a[n]){ return true; } return false; } private static void show(int[] a) { System.out.print("排序结果"); for(int i=0;i<a.length;i++){ System.out.print(a[i]+","); } } }
三:总结
插入排序对于部分有序的数组十分高效,也十分适合于小规模数组,部分有序的意思数组中倒置的数量小于数组大小的某个倍数,典型的部分有序数组为:
- 数组中每个元素距离它最终的位置不远。
- 一个有序的大数组接一个小数组。
- 数组中只有几个元素的位置不确定。