3.2【设计型】有一个已排好序的数组(如{5, 12, 22, 34, 45, 55, 67, 78, 89, 98}),要求输入一个数后,按原来排序的规律将它插入到该数组中,然后求采用二分法查找新插入的数所在位置(下标)。假设:所有的数都互不相同。
看下这个代码,稍加修改就可以实现你的功能了。
#include <iostream>
#include <string.h>
using namespace std;
void rnk(int x[20],int n) {
int p = 0;
for (int i = 0; i < n; i++) {
for (p = 0; p < n-1-i; p++) {
if(x[p] > x[p + 1])
{
int tmp = 0;
tmp = x[p];
x[p] = x[p + 1];
x[p + 1] = tmp;
}
}
}
for (int i = 0; i < n; i++) {
cout << x[i] << endl; }
}
int main()
{
int a[20], t, i ,n= 0;
char huiche;
memset(a, 0, sizeof(a));
while (cin >> t) {/*输入任意个整数(小于20个)*/
huiche=(char)t;
if(huiche == '\xA')break;
a[i] = t;
n++;
i++;
}
rnk(a,n);
}