Problem Description
有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。
Input
输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。
Output
对于每个测试实例,输出插入新的元素后的数列。
Sample Input
3 3 1 2 4 0 0
Sample Output
1 2 3 4
笔记
由于是有序序列,所以考虑二分查找填空。
代码如下:
#include<iostream>
#define MAXINT 0x7fffffff
#define MININT 0x80000000
using namespace std;
int a[120];
void Insert(int, int);
int binary_search(int, int ,int);
int main(){
int n, m, i;
a[0] = MININT;
while( cin >> n >> m, n != 0 || m != 0){
for(i = 1; i <= n; ++i) cin >> a[i];
a[n+1] = MAXINT;
Insert(n, m);
}
return 0;
}
/** Binary version */
void Insert(int n, int m){
int insertIndex = binary_search(1, n+1, m);
for(int i = 1; i <= n; ++i){
if(i == insertIndex) cout << m << " ";
cout << a[i] << " ";
}
if(insertIndex == n+1) cout << m << " ";
cout << endl;
}
int binary_search(int startIndex, int endIndex, int value){
int midIndex = ( startIndex + endIndex ) / 2;
if ( a[midIndex-1] < value && value <= a[midIndex] ) return midIndex;
if ( a[midIndex] < value ) return binary_search(midIndex+1, endIndex, value);
if ( a[midIndex-1] >= value ) return binary_search(startIndex, midIndex-1, value);
return -1;
}