#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;
}
}
温馨提示:内容为网友见解,仅供参考