比直插有所改善,直插是一次次的进行判断移动。可以先找出插入的位置再移动,其实就是在有序数组中找位置
在已排好序的子序列中插入新元素并排序
void InsertSort(int a[], int len) {
int i, j, low, high, mid, temp;
for (i = 1; i <= len - 1; i++) {//下标1~len-1都需要排序
temp = a[i];
low = 0; high = i - 1;//已排好序的子序列
while (low <= high) {//先确定插入的位置 //l=h还要进行一次
mid = (low + high) / 2;
if (temp < a[mid]) high = mid - 1;
else low = mid + 1;
}//返回最大且不大于temp的元素的位置/下标
//cout << low << " " << mid << " " << high << endl;
//新元素小于子序列才会移动。不小于有high+1=i,不会进行
for (j = i - 1; j >= high + 1; j--)
a[j + 1] = a[j];
a[high + 1] = temp;
}
}
void test02() {
int a[] = { 1,2,3,4,5,6,7,8,9,10,5 };
InsertSort(a, sizeof(a) / sizeof(*a));
for (const int i : a)cout << i << ' '; cout << endl;
}