顺序查找-比较简单,循环比较即可
- /*Find*/
- //顺序查找算法,循环比较即可
- #include <iostream>
- #include <time.h>
- #define N 15
- using namespace std;
- int Search(int a[],int n,int key)
- {
- int i,f=-1;
- for(i=0;i<n;i++)
- {
- if(key==a[i])
- {
- f=i;
- break;
- }
- }
- return f;
- };
- int main() {
- cout<<"hello"<<endl;
- int shuzi[N];
- srand(time(NULL));
- for(int i=0;i<N;i++)
- {
- shuzi[i]=rand()%100;
- }
- cout<<"************show the data*************"<<endl;
- for(int i=0;i<N;i++)
- {
- cout<<shuzi[i]<<" ";
- }
- cout<<endl;
- cout<<"input the number you want to find"<<endl;
- int temp;
- cin>>temp;
- int pos = Search(shuzi,N,temp);
- if(pos<0)
- {
- cout<<"can't find the data!"<<endl;
- }
- else
- {
- cout<<"the data is located in SHUZI at "<<pos+1<<endl;
- }
- return 0;
- }
折半查找-适用于有序的数据的查询
- /*折半查找*/
- #include <iostream>
- using namespace std;
- #define N 15
- int Search(int a[],int n,int key)
- {
- int mid,low,high;
- low = 0;
- high = n-1;
- while(low<=high)
- {
- mid = (low+high)/2;
- if(a[mid]==key)
- return mid;
- else
- {
- if(a[mid]>key)
- high = mid-1;
- if(a[mid]<key)
- low = mid+1;
- }
- }
- return -1;
- }
- int main()
- {
- int shuzi[N]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
- /*srand(time(NULL));
- for(int i=0;i<N;i++)
- {
- shuzi[i]=rand()%100;
- }*/
- cout<<"************show the data*************"<<endl;
- for(int i=0;i<N;i++)
- {
- cout<<shuzi[i]<<" ";
- }
- cout<<endl;
- cout<<"input the number you want to find"<<endl;
- int temp;
- cin>>temp;
- int pos = Search(shuzi,N,temp);
- if(pos<0)
- {
- cout<<"can't find the data!"<<endl;
- }
- else
- {
- cout<<"the data is located in SHUZI at "<<pos+1<<endl;
- }
- return 0;
- }