顺序查找
#include<iostream>
using namespace std;
int SequenceSearch(int a[], int value, int n)
{
int i;
for(i=0; i<n; i++)
if(a[i]==value)
return i;
return -1;
}
int main()
{
int a[8] = {1,23,4,5,6,7,34,9};
int n =8 ;
int value =9;
cout<<SequenceSearch(a,value,n)<<endl;
//return SequenceSearch(a,value,n);
return 1;
}
二分查找
#include<iostream>
using namespace std;
//二分查找(折半查找),版本1
int BinarySearch1(int a[], int value, int n)
{
int low, high, mid;
low = 0;
high = n-1;
while(low<=high)
{
mid = (low+high)/2;
if(a[mid]==value)
return mid;
if(a[mid]>value)
high = mid-1;
if(a[mid]<value)
low = mid+1;
}
return -1;
}
//二分查找,递归版本
int BinarySearch2(int a[], int value, int low, int high)
{
int mid = low+(high-low)/2;
if(a[mid]==value)
return mid;
if(a[mid]>value)
return BinarySearch2(a, value, low, mid-1);
if(a[mid]<value)
return BinarySearch2(a, value, mid+1, high);
}
int main()
{
int a[8] = {1,23,4,5,6,7,34,9};
int n =8 ;
int value =6;
int low =0;
int high = 7;
cout<<BinarySearch1(a,value,n)<<endl;
cout<<BinarySearch2(a,value,low,high)<<endl;
//return SequenceSearch(a,value,n);
return 1;
}