本程序较平常的返回目标数所在数列中的位置,包含了目标数在已知数列中找不到时,则返回将其插入到原数列的位置。
#include<stdio.h>
#include<iostream>
using namespace std;
int a[1000],n;
bool target_Exit = 1;//初始状态假设所查找的数在目标序列
int binary(int head,int tail,int target){
int midindex = (head + tail)/2;
if(target > a[midindex]){
if(target<a[midindex+1]){//如果目标数是介于a[midindex]和a[midindex+1]之间,则返回下标至midindex+1;
target_Exit = 0;//目标数不存在,将target_Exit置为0;
return midindex + 1;
}
head = midindex + 1;
binary(head,tail,target);
}
else if(target < a[midindex]){
if(target > a[midindex-1]){//如果目标数是介于a[midindex]和a[midindex-1]之间,则返回下标至midindex;
target_Exit = 0; //目标数不存在,将target_Exit置为0;
return midindex;
}
tail = midindex - 1;
binary(head,tail,target);
}
else return midindex;
}
void quicksort(int left, int right){
if(left > right)return;
int i = left;
int j = right;
int temp = a[left];
while(i!=j){
while(i<j && a[j]>=temp){
j--;
}
while(i<j && a[i]<=temp){
i++;
}
if(i<j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
a[left] = a[i];
a[i] = temp;
quicksort(left,i-1);
quicksort(i+1,right);
}
int main(){
cout<<"请输入一共有多少个数:" ;
cin >> n;
cout<<"请依次输入"<<n<<"个数,中间用空格或回车隔开:"<<endl;
for(int i=0; i<n; i++){
cin >> a[i];
}
quicksort(0,n-1);
cout<<"排序之后的数列为:"<<endl;
for(int i = 0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<"\n";
int tar;
cout<<"请输入要查找的数:";
cin >> tar;
int result = binary(0,n,tar)+1;//目标数的位置应为数组下标+1
//cout<<tar_Exit<<endl;
if(target_Exit){
cout<<"目标数在数列中的第"<<result<<"位"<<endl;
}
else{
cout<<"目标数不在数列中,应将其插入在第"<<result<<"位"<<endl;
}
return 0;
}
运行截图: