数据结构与算法 ---- 折半插入排序

it2026-06-05  5

#include <stdio.h> void BInsertSort(int a[], int n); int main() { int i; int a[10] = {2,6,2,9,4,0,18,7,1,5}; BInsertSort(a,10); for(i=0; i<10; i++) printf("%d ",a[i]); return 0; } void BInsertSort(int a[], int n) { int low, high,mid,temp; for(int i=1; i<n; i++){ low=0; high=i-1; temp=a[i]; //采用折半查找法判断插入位置,最终变量 low 表示插入位置 while(low<=high){ mid=(low+high)/2; if(a[mid]>temp) high=mid-1; else low=mid+1; } //有序表中插入位置后的元素统一后移 for(int j=i; j>low; j--) a[j]=a[j-1]; a[low]=temp;//插入元素 } }
最新回复(0)