思路:
设定查找范围的下限low,上限high,
由此确定查找范围的中间位置mid;
中间位置的值等于待查的值,查找成功
中间位置的值小于待查的值,low=mid+1
中间位置的值大于待查的值,high=mid-1
直到low>high,查找失败。
迭代代码:
#include <iostream>
using namespace std;
int bin_search(int str[], int n, int key){ //迭代
int mid;
low = 0;
high = n-1;
while(low <= high){
mid = (low + high)/2;
if(str[mid] == key)
return mid; //查找成功
if(str[mid] < key)
low = mid+1;
if(str[mid] > key)
high = mid-1;
}
return -1; //查找失败
}
int main(){
int key,add,n;
int str[n];
cout << "请输入查找关键字:";
cin >> key;
cout << "请输入数组大小:";
cin >> n;
for(int i=0; i < n; i++)
cin >> str[i]; //输入数组
add = bin_search(str, n, key);
cout << add;
return 0;
}
递归代码:
#include <iostream>
using namespace std;
int bin_search(int str[], int low, int high, int key){ //递归
int mid;
if(low > high)
return -1; //查找失败
else{
mid = (high + low)/2;
if(str[mid] == key)
return mid; //查找成功
else if (str[mid] < key)
return bin_search(str, mid+1,high, key);
else
return bin_search(str, low, mid-1, key);
}
}
int main(){
int key,add,n;
int str[n];
cout << "请输入查找关键字:";
cin >> key;
cout << "请输入数组大小:";
cin >> n;
for(int i=0; i < n; i++)
cin >> str[i]; //输入数组
add = bin_search(str, 0, n-1, key);
cout << add;
return 0;
}