顺序查找和二分查找
#include<iostream>
using namespace std;
#define Maxsize 100
class Date{
public:
int date[Maxsize + 1]; /*存储时按照1到n下标存储,空出下标为0的位置*/
};
int mindsearch(Date&A, int k, int n); /*按二分查找*/
int sequentialsearch(Date &A, int k, int n); /*按顺序查找*/
int main(){
Date A;
int i,n,k,j;
cin >> n;
for (i = 1; i < n + 1; i++)
cin >> A.date[i];
cout << "输入查找的数k:";
cin >> k;
j=sequentialsearch(A, k, n);
if (j == 0)
cout << "按顺序查找,未查找到" << k << endl;
else
cout <<"按顺序查找"<< k << "在第" << j << "个位置" << endl;
j = mindsearch(A, k, n);
if (j == 0)
cout << "二分查找,未查找到" << k << endl;
else
cout << "二分查找" << k << "在第" << j << "个位置" << endl;
return 0;
}
int sequentialsearch(Date &A, int k,int n){
A.date[0] = k;
int i;
for (i = n;A.date[i]!=k; i--);
return i; /*未找到返回0,找到返回下标*/
}
int mindsearch(Date&A,int k,int n){
int right = n, left = 1;
int mind;
while (left<=right){
mind = (left + right) / 2;
if (A.date[mind] == k)
return mind;
else if (A.date[mind] < k)
left = mind + 1;
else
right = mind - 1;
}
return 0; /*没找到返回0*/
}