我们来自五湖四海,不为别的,只因有共同的爱好,为中国互联网发展出一分力!

使用c语言指针和递归方法实现二分查找

2014年05月12日01:10 阅读: 33848 次

标签: 使用c语言指针和递归方法实现二分查找

1

使用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
#include
//binary search init
int binsearch(int low, int height, int *ptr, int);
int main(){
????int i = 0;
????int arr[10];
????int *ptr=arr;
????for(i=0;i<10;i++)
????????scanf("%d",arr+i);
????printf("the input data is:\n");
????for(i=0;i<10;i++)
????????printf("%d",arr[i]);
????printf("\n开始折半查找\n");
????printf("\n输入要查找的数\n");
????int m;
????scanf("%d",&m);
????int j;
????j = binsearch(0,9,ptr,m);
????printf("\n*ptr=%d,j=%d\n",*ptr,j);
????return 0;
}
?
int binsearch(int low,int height, int *ptr, int value){
????if (ptr == NULL || low > height) return -1;
????printf("\nlow=%d,height=%d,\n",low,height);
????if(*(ptr+low) == value) { ptr+=low; return low;}
????if(*(ptr+height) == value) { ptr+=height; return height;}
????if(low == height){
????????printf("low==height = %d",low);
????????if(*(ptr+low) == value) { ptr+=low; return low;}
????????else return -1;
????}??
????int mid = (low + height) / 2;
????int result;
????printf("\nlow=%d,height=%d,mid=%d\n",low,height,mid);
????printf("*(ptr+mid)=%d,value=%d",*(ptr+mid),value);
????// 还得防止当查所的值不存在时,由于递归引起的无限循环
????if(*(ptr+mid) == value) {
????????printf("return mid = %d",mid);
????????ptr+=mid;
????????return mid;
????}??
????else if(*(ptr+mid) > value) {return binsearch(low,mid-1,ptr,value);}
????else {return binsearch(mid+1,height,ptr,value);}
????return -1;
}

分享到: 更多
?2019 安全焦点 版权所有.