//by 温柔床乃英雄冢
//谭浩强第二版习题5.4
int a[] = {2,5,12,50,99,101,500};//已知顺序的序列,插入新值
const int n = 7;
int head = 0;
int tear = n-1;
int mid;
int x, rank;
cout << "input:";
cin >> x;
while (a[head] < x&&x < a[tear]) {//采用二分法提高时效
if (tear - head <= 1)//防止进入死循环
break;
mid = (head + tear) / 2;
if (a[mid] <= x) {
head = mid;
}
else {
tear = mid;
}
}
if (x < a[head]) {
rank = head;//大小差别1
}
else if (x>a[tear]) {
rank = tear + 1;//3
}
else {
rank = tear;//2
}
for (int i = 0; i < rank; i++) {//采用从rank处分割,"插入输出x"
cout << a[i] << " ";
}
cout << x << " ";
for (int i = rank; i < n; i++) {
cout << a[i]<<" ";
}
二分法插队
最新推荐文章于 2024-04-27 22:01:31 发布