假设数组a[N]已经排好序,现在需要插入一个新的数。假设我们将数插入某个位置,那么这个位置之后的所有元素都必须后移一位。
例如我们要将2插入升序序列{1,3,4,5}中,结果是{1,2,3,4,5}。
1、与原序列相比,相当将插入位置及之后的{3,4,5}整体右移了一位{1,__ ,3,4,5}。
2、我们只能从后往前一个一个移动,即{1,3,4,5,__ }、{1,3,4,__ ,5}、{1,3,__ ,4,5}。
3、实际上它等价于从后往前查找,每找到一个比目标值大的数,就将它后移一位。过程类似于挖坑填坑。
因此,插入一个数到有序数列中的代码为:
/*
* 从start到needInsert-1已经升序排列
*/
private static void insertToAsc(int[] almostSorted,int start,int needInsert){
int t=almostSorted[needInsert];
int j=needInsert-1;
while(j>=start&&t<almostSorted[j]){
almostSorted[j+1]=almostSorted[j];
j--;
}
almostSorted[j+1]=t;
}
由此,直接插入排序的完整代码为:
public static void straightInsertSort(int[] nums,int start,int end){
if(nums==null||nums.length<=end) throw new IllegalArgumentException("输入不合法");
int t,j;
for(int i=start+1;i<=end;i++){
j=i-1;
t=nums[i];
while(j>=start&&t<nums[j]){
nums[j+1]=nums[j];
j--;
}
nums[j+1]=t;
}
}
插入排序的一个可能的改进是利用二分查找找到升序数组中第一个比目标值大的位置。它可以减少比较的次数,但是性能是否提升还不能理解。
public static void binaryInsertSort(int[] nums,int start,int end){
if(nums==null||nums.length<=end) throw new IllegalArgumentException("输入不合法");
int t,j,k;
for(int i=start+1;i<=end;i++){
t=nums[i];
j=BinarySearch.findFirstBigger(nums, start, i-1, t);
k=i-1;
while(k>=j){
nums[k+1]=nums[k];
k--;
}
nums[k+1]=t;
}
}