使用C語言指針和遞歸方法實現二分查找,符輸入語句與打印語句。
#include<stdio.h>
//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;
}
C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm
讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm
讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm
讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm
將C語言梳理一下,分布在以下10個章節中: