c++语言中,输入n个数从小到大排序,然后利用折半查找,在这个有序序列中,查找用户输入的某个整数d。

帮忙啊高手

#include <iostream>
using namespace std;

void InsertSort(int A[] , int n)//插入排序
{
int i,j,temp;
for(i=1;i<n;i++)
{
j=i;
temp=A[i];
while(j>0&&temp<A[j-1])
{
A[j]=A[j-1];
j--;
}
A[j]=temp;
}
}

int BinSearch(int A[] , int n, int key)//二分查找
{
int mid,low,high,midValue;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
midValue=A[mid];
if(key==midValue)
return mid;
else if(key<midValue)
high=mid-1;
else
low=mid+1;
}
return -1;
}

void main()
{
int n,i,key,j;
cout<<"请输入要排序的数的个数:";
cin>>n;
int *a=new int[n];
cout<<"请输入要排序的数:";
for(i=0;i<n;i++)
{
cin>>a[i];
}

cout<<"排序后的数为:";
InsertSort(a,n);
for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}

cout<<endl;
cout<<"请输入要查找的数:";
cin>>key;
j=BinSearch(a,n,key);
if(j==-1){
cout<<"未查到你要找的数!";
}
else{
cout<<"此数组中存在你要查找的数。"<<endl;
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-03-24
用STL中的sort和binary_search两个算法。追问

具体怎么写啊

追答

vector v;
//读入n个数到v中...
sort (v.begin(), v.end());//从小到大排序
//读入用户输入的某个整数d...
if (binary_search (v.begin(), v.end(), d))
cout<<"在有序序列中找到d!"<<endl;
else
cout<<"在有序序列中没找到d!"<<endl;

相似回答