1. 程式人生 > >C語言之折半查詢

C語言之折半查詢

//折半查詢
#include "stdio.h"
 int find(int num,int arr[])
 {
 	int xiabiao=-1;
 	int low=0;
 	int high=8;
 	int mid=(low+high)/2;
 	while(low<=high)
 	{
 		if(num==arr[mid])
 		{
 			xiabiao=mid;
 			break;
		 }
 		else if(num>arr[mid])
 		low=mid+1;
 		else
 		high=mid-1;
 		mid=(low+high)/2;
	}
	if(xiabiao==-1)
	{
		printf("沒有這個數字");
	}
	else
	printf("有這個數字的並且這個數字的下標為%d\n",xiabiao);
 }
 int main()
 {
 	int arr[9]={1,25,36,21,41,47,58,96,36};
 	find(41,arr);
 	return 0;
  }