CFDHȻٻO(n2)ʱɼӷ㼴ɡƷ㷨ʵ־˷ʱܡܷٸĽ㷨
ϰ5
1. ۰㷨ȷȷ㷨ȷ֤ȷ
˵ԭ
int BinSearch(int r[ ], int n, int k) {
int low = 0, high = n - 1; int mid;
while (low <= high) {
mid = (low + high) / 2; if (k < r[mid]) high = mid;
else if (k > r[mid]) low = mid;
else return mid; }
return 0; }
ȷ㷨
int BinSearch1(int r[ ], int n, int k) {
int low = 0, high = n - 1; int mid;
while (low <= high) {
mid = (low + high) / 2; if (k < r[mid]) high = mid - 1;
else if (k > r[mid]) low = mid + 1;
else return mid; }
return 0; }
2. д۰ҵĵݹ㷨ʱܡ
//۰ҵĵݹʵ
#include
int digui_search(int a[],int low,int high,int x) {
if (low > high) return 0;
int mid = (low+high)/2; if (a[mid] == x) return mid;
else if (a[mid] < x)
digui_search(a,low,mid-1,x); else
digui_search(a,mid+1,high,x); }
int main() { int a[6]={0,1,2,9,5,3}; int result=digui_search(a,0,5,5);
cout< 3. ۰㷨ʹܹ֮зΧҡνΧҪҳڸֵab֮ Ԫأab ĵڶ㷨ʵ֣ //۰㷨ʹܹ֮зΧ #include //۰зΧҺ void digui_search(int min, int max, int a[], int low, int high) { int mid; mid=(low+high)/2; if(a[mid] digui_search(min, max, a, mid, high); else if(a[mid]>max) digui_search(min, max, a, low, mid); else {