因为王道是对数组下标[1,n]进行排序,本文是对下标为[0,n-1]进行排序,故对数组下标做一定改变。
private void InsertSort(int[] A,int n){ //本文数组长度为n,书中数组长度为n+1
for(int i=1;i<n;i++){ //从A[1]开始向前插入
int temp=A[i]; //temp暂存当前遍历到的元素
int low=0,higt=i-1; //low在这里做出改变
while(low<=high){ //不断根据temp与A[mid]的比较,改变high和low的值
int mid=(low+high)/2;
if(A[mid]>temp) high=mid-1;
else low=mid+1;
}
for(int j=i-1;j>=high+1;j--){ //此时 low=high+1,应当将temp暂存的值放到二者之间,故将包括下标high+1在内的所有元素后移
A[j+1]=A[j];
}
A[high+1]=temp; //这里的high+1同样等于low
}
}```