一、概念
折半查找(Binary Search)的查找过程是:先确定待查找记录所在的范围区间,然后逐步 缩小范围直到找到或找不到记录为止。该方法的局限性在于要排序的查找表必须有序,即
如若i<j 那么a(i)<=a(j);
二、C语言编程实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
//
// main.c
// BinarySearchDemo
//
// Created by zhanggui on 15/7/19.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#include <stdio.h>
#include <time.h>
#define N 20
int
BinarySearch(
int
a[],
int
n,
int
found)
{
int
low = 0;
int
high = n-1;
int
mid;
// time_t startTime,endTime; //用于计算运行时间
// startTime = clock();
while
(low <= high) {
mid = (low+high)/2;
if
(found==a[mid]) {
printf
(
"-------------------\n"
);
// endTime = clock();
// double Total_Waste_Time = (double)(endTime-startTime)/CLOCKS_PER_SEC;
// printf("花费时间为:%f",Total_Waste_Time);
return
mid;
}
else
if
(found<a[mid])
{
high = mid - 1;
}
else
{
low = mid+1;
}
}
// endTime = clock();
// double Total_Waste_Time = (double)(endTime-startTime)/CLOCKS_PER_SEC;
// printf("花费时间为:%f",Total_Waste_Time);
return
-1;
}
int
main(
int
argc,
const
char
* argv[]) {
int
found;
int
a[N] = {3,4,5,6,7,8,9,10,14,15,18,20,31,43,56,67,84,90,92,96};
printf
(
"请输入一个数:"
);
scanf
(
"%d"
,&found);
int
i = BinarySearch(a, N, found);
if
(i != -1) {
printf
(
"在数组中的位置是%d\n"
,i);
}
else
{
printf
(
"没有找到"
);
}
return
0;
}
|