#include<stdio.h>
#include<windows.h>
int binSearch(int arr[], int size, int x)
{
int left = 0;
int right = size - 1;
int mid = 0;
while (left <= right)
{
mid = left + ((right - left) / 2);
if (x > arr[mid])
{
left = mid + 1;
}
else if (x < arr[mid])
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int size = sizeof(arr) / sizeof(arr[0]);
int x = 6;
int index = binSearch(arr, size, x);
if (index < 0)
{
printf("not found!\n");
return 1;
}
printf("found it:%d\n", index);
system("pause");
return 0;
}
写一个函数,实现一个整形有序数组的二分查找
最新推荐文章于 2023-06-12 16:03:27 发布