问题描述
折半插入排序
代码
#include<stdio.h>
#define N 1001
void InsertSort(int a[],int n);
int main(void) {
int n;
int a[N];
scanf("%d",&n);
for(int i=1; i<=n; i++) {
scanf("%d",&a[i]);
}
InsertSort(a,n);
for(int i=1; i<=n; i++) {
printf("%d ",a[i]);
}
printf("\n");
return 0;
}
void InsertSort(int a[],int n) {
int i,j,low,high,mid;
for(i=2; i<=n; i++) {
a[0]=a[i]; //将a[i]暂存到a[0]
low=1;
high=i-1;
while(low<=high){ //折半查找(默认递增有序)
mid=(low+high)/2;//取中间点
if(a[mid]>a[0]) {
high = mid-1;//查找左半区间
}else{
low = mid+1;//查找右半区间
}
}
for(j=i-1; j>=high+1; --j) {
a[j+1]=a[j]; //统一后移元素 ,空出插入位置
}
a[high+1]=a[0]; //插入操作
}
}