第三步,此时的中间元素的索引是7的值8,即为我们我查找的值。
/* File Name: Binary Search Data Time: Anthor: */ #include <stdio.h> #include <stdlib.h> #define MAX 21 typedef struct element { int key; }record; record data[AMX] = { 2, 5, 7, 9, 17, 21, 25, 33, 46,89,100, 121, 127, 139, 237, 279, 302, 356, 455, 467, 500}; // int binary_find(int key, int low, int high) { int mid; if(low == high) { if(data[low].key == key) return low; else return -1; } else { mid = (low + high) / 2; if(mid == low); mid++; if(key < data[mid].key) return binary_find(key, low, mid - 1); else return binary_find(key, mid, high); } } //Binary Search int binary_search(int key) { return binary_find(key, 0, MAX - 1); } int main(int argc, char** argv) { int found; int value; while(1) { printf("\n请输入查找值(0-500) ==> "); scanf("%d", &value); if(value != -1) { found = binary_search(value); if(found != -1) { printf("找到查找值: %d[%d]\n", value, found); } else { printf("没有哦找到查找值: %d\n", value); } } else exit(1); } system("pause"); return 0; }
此处是使用递归的方式实现的折半查找。
以下可以通过使用非递归的方式实现折半查找
代码实现如下:
/*
File Name: Binary Search
Data Time:
Anthor:
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX 21
typedef struct element
{
int key;
}record;
record data[MAX] = {
2, 5, 7, 9, 17, 21, 25,
33, 46,89,100, 121, 127, 139,
237, 279, 302, 356, 455, 467, 500};
int binary_search(int key, int low, int high)
{
int mid;
while(low <= high)
{
mid = (low + high) / 2;
if(key < data[mid].key)
high = mid - 1;
else
if(key > data[mid].key)
low = mid + 1;
else
return mid;
}
return -1;
}
int main(int argc, char** argv)
{
int found;
int value;
while(1)
{
printf("\n请输入查找值(0-500) ==> ");
scanf("%d", &value);
if(value != -1)
{
found = binary_search(value, 0, MAX - 1);
if(found != -1)
{
printf("找到查找值: %d[%d]\n", value, found);
}
else
{
printf("没有哦找到查找值: %d\n", value);
}
}
else
exit(1);
}
system("pause");
return 0;
}