C语言 -- 折半查找小程序
#include <stdio.h>
int searchNum(int *arr, int num, int len);
int main(int argc, const char * argv[]) {
int a[9] = {3, 0, -5, 88, 99, 100, -10, 50, 20};
int i = 0, j = 0;
int num;
printf("please input a number: \n");
scanf("%d", &num);
int temp;
int length = sizeof(a) / sizeof(a[0]);
for(; i < length; i++){
for(j = i + 1; j < length; j++){
if(a[i] > a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int res = searchNum(a, num, length);
if(res != -1){
printf("Find it.\n");
}else{
printf("Not found.\n");
}
return 0;
}
int searchNum(int *arr, int num, int len){
int max = len-1, min = 0;
int mid = (max + min) * 0.5;
while(num != arr[mid]){
if(num > arr[mid]){
min = mid + 1;
}else if(num < arr[mid]){
max = mid - 1;
}
if(min > max){
return -1;
}
mid = (max + min) * 0.5;
}
return mid;
}