1. 程式人生 > >二分搜尋的遞迴實現

二分搜尋的遞迴實現

/*遞迴二分查詢*/
#include<stdio.h>
int select(int a[],int low,int high,int key);
void main(){
	int a[10]={11,21,31,41,51,61,71,81,91,101};
	int low=0,high=9;
	int key;
	printf("請輸入要查詢的數:");
	scanf("%d",&key);
	int num=select(a,low,high,key);  //定義num接收select函式的返回值
	if(num==-1){
		printf("查詢失敗!");
	}else{
		printf("該數是第 %d 個數。",num);
	}
}
//low:陣列第一個位置   high:最高    key:要查詢的數
int select(int a[],int low,int high,int key){
	if(low<=high){
		int mid=(low+high)/2;
		if(a[mid]==key){
			return mid;
		}else if(a[mid]<key){
			//移動low,high
			return select(a,mid+1,high,key);
		}else{
			return select(a,low,mid-1,key);
		}
	}else
		return -1;
}