#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
int n,rec[100],Key;
void Binary_search(int Key)
{
int mid,low,high,find;
low = 0;high = n-1;find = 0;
while (!find && low <= high)
{
mid = (low + high) / 2;
if (Key == rec[mid])
{
printf("Successfully searched! The index is:%d\n", mid);
find = 1;
}
else if (Key < rec[mid]) high = mid - 1;
else low = mid + 1;
}
if (find == 0) printf("Search Failed!\n");
}
int Binary_search1(int K, int low, int high)
{
if (low > high) return -1;
int mid = (low + high) / 2;
if (K == rec[mid]) return mid;
else if (K < rec[mid]) return Binary_search1(K, low,mid-1);
else return Binary_search1(K,mid+1,high);
}
int main()
{
printf("Please input the number N of records(integers)\n");
printf("N = ");
scanf("%d", &n);
printf("Please input N records\n");
for (int i=0;i<n;i++)
scanf("%d", &rec[i]);
printf("Please input the key you want to find\n");
printf("Key = ");
scanf("%d", &Key);
printf("Recursive Method:\n");
Binary_search(Key);
printf("Non-recursive Method:\n");
int result = Binary_search1(Key,0,n-1);
if (result == -1)
printf("Search Failed!\n");
else
printf("Successfully searched! The index is:%d\n", result);
}
折半查找
最新推荐文章于 2021-01-15 11:21:30 发布
