题目:使用二分查找,查找一个数是否存在于一个升序数组中
#include <stdio.h>
int binarySearch(int arr[], int length, int elem);
int main()
{
int arr[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int key;
int length = sizeof(arr) / sizeof(arr[0]);
printf("请输入要查找的元素:\n");
scanf_s("%d", &key);
int mid = binarySearch(arr, length, key);
if (mid != -1) {
printf("找到了该数, 数组下标为:%d", mid);
}
else {
printf("未找到该数");
}
return 0;
}
int binarySearch(int arr[], int length, int elem) {
int low = 0, high = length - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == elem) {
return mid;
}
else if (arr[mid] > elem) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}