对于有序数组而言,二分查找效率是最高的。
# include <iostream>
using namespace std;
//递归
void RecursiveBinarySearch(int arr[],int low,int high,int target){
int mid = (low + high)/2;
if(low > high){
cout << "查找失败!" << endl;
return;
}
if(arr[mid] == target){
cout << arr[mid] << "查找成功!" << endl;
return;
}
else{
if(target < arr[mid])
RecursiveBinarySearch(arr,low,mid - 1,target);
else
RecursiveBinarySearch(arr,mid + 1,high,target);
}
}
//非递归
void NonRecursiveBinarySearch(int arr[],int low,int high,int target){
int mid = (low + high)/2;
while(low <= high){
if(arr[mid] == target){
cout << arr[mid] << "查找成功!" << endl;
return;
}
if(arr[mid] < target){
low = mid + 1;
mid = (low + high)/2;
}
if(arr[mid] > target){
high = mid - 1;
mid = (low + high)/2;
}
}
cout << "查找失败!" << endl;
}
int main(){
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
NonRecursiveBinarySearch(arr,0,9,7);
return 0;
}