折半查找的手工过程:
1.我需要查找的数是10;
给定:1 5 8 10 13 14 17 22 25 27 29 31 35 37 40 42 45 47 50 51 58
下标:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
h m t
h m t
h m t
h t
m h
m
这个手工过程到head = tail 时找到了。
我需要查找的数是29;
给定:1 5 8 10 13 14 17 22 25 27 29 31 35 37 40 42 45 47 50 51 58
下标:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
h m t
这个手工过程数在head < tail时程序停止,找到的是下标的那个数。
代码如下:
#include<stdio.h>
#include<stdlib.h>
int binarySearch(int *arr,int count ,int data){
int middle;
int head = 0;
int tail;
tail = count;
while(arr[middle] != data){
middle = (head + tail)/ 2;
if(arr[middle] < data){
head = middle + 1;
}else if(arr[middle] > data){
tail = middle - 1;
}
}
return middle;
return -1;
}
int main(){
int n = 0;
int m ;
int a[10]={1,4,8,9,16,17,19,20,25,27};
printf("请输入需要查找的数: ");
scanf("%d",&n);
m = binarySearch(a,10,n);
printf("%d ",m);
return 0;
}
这是一个简单的折半处理,用的是一个简单的数组
需要强调的是:
如果要运用折半算法,数必须是有序的(升序或者降序)
很多人都认为while(head > tail)这样也是正确的,但是对于middle = data时条件一直成立就会出现问题的!