折半插入排序思想:
-
在排序第i个数时,前i-1个数已经排序完成,这是折中排序的前提,所以在开始排序时起始位置为i=1
-
折中排序,顾名思义就是折中,所以在折中排序时,先要以谁开头以谁结尾,所以需要定义两个变量front,end,有了这两个变量才能够找到他们的中间值mid
-
排序的最终目的还是找到i的最终插入位置,本代码要求升序排序,所以只需找到比下标为i的数小的数的下标
-
以此时只需将mid的值与i的值作比较,如果arr[i]<arr[mid]的话,此时说明下标为i的插入位置为[0,mid-1]所以end的位置,应该为mid-1,依次类推,反之则front的位置为mid+1
-
当front值大于end值的时候则此时说明找到了下标为i的数的插入位置,位置为front
-
找到插入位置后只需将i-1到front的数向后移动一位,则此时front的位置空出来之后,将下标为i的值插入就完成了排序
代码如下:
binaryInsertSort(int arr[],int len){
int front,end,temp;
for(int i=1;i<len;i++){
temp = arr[i];
front = 0;
end = i - 1;
while(front <= end){
int mid;
mid =(front + end)/2;
if(temp < arr[mid]){
end = mid -1;
}else{
front = mid +1;
}
}
for(int z=i;z>front;z--){
arr[z] = arr[z-1];
}
arr[front]=temp;
}
}