模块与群体数据3
#include<iostream>
using namespace std;
template<class T>
void mySwap(T&x,T&y)
{
T temp=x;
x=y;
y=temp;
}
template<class T>
void bubblesort(T a[],int n)
{
int i=n-1;
while(i >0)
{
int lastExchangeIndex=0;
for(int j=0;j<i;j++)
if(a[j+1]<a[j])
{
mySwap(a[j],a[j+1]);
lastExchangeIndex=j;
}
i=lastExchangeIndex;
}
}
template<class T>
int BinSearch(const T list[],int n,const T key)
{
int low=0;
int high=n-1;
while(low<=high)
{
int mid=(low+high)/2;
if(key==list[mid])
return mid;
else if(key>list[mid])
low=mid+1;
else
high=mid-1;
}
return -1;
}
int main()
{
int key,mid,n=20;
int i;
int data1[]={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20};
cout<<"数组排序后:"<<endl;
bubblesort(data1,n);
for(i=0;i<20;i++)
{
cout<<data1[i]<<",";
}
cout<<endl;
cout<<"请输入key:"<<endl;
cin>>key;
cout<<key<<"在数组第:"<<BinSearch(data1,n,key)+1<<"个数字"<<endl;
}