可以在整型有序数组中查找想要的数字,找到了返回下标,找不到返回-1
代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int BinarySearch(int arr[],int left,int right,int key){
int mid;
while (left < right){
//折半查找:中间数=头加尾/2
mid = (left + right) / 2;
//若大于所求数,则尾的下标改为中间数-1
if (arr[mid]>key){
right = mid - 1;
}//若小于所求数,则头的下标改为中间数+1
else if (arr[mid]<key){
left = mid + 1;
}
else{
return mid;
}
}
return -1;
}
int main(){
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0])-1;//right是下标
int key = 14;
int result = BinarySearch( arr, left, right, key);
if (result == -1){
printf("找不到\n");
}
else {
printf("找到了,下标是:%d\n", result);
}
system("pause");
return 0;
}
运行结果: