二分法是一种在有序数组中快速查找目标元素的方法,每次可以排除数组中当前元素的一般的元素个数
int main()
{
int arr[20] = { 1,2,3,5,7,8,10,14,23,46 };
int sz = sizeof(arr) / sizeof(arr[0]);
int left = 0;
int right = sz - 1;
int input = 0;
int mid = 0;
printf("请输入要寻找的数字:\n");
scanf("%d", &input);
while (left <= right)
{
int mid = left + (right - left) / 2;
if (input > arr[mid])
{
left = mid +1;
}
else if (input < arr[mid])
{
right = mid - 1;
}
else
{
printf("找到了,就是第%d个元素\n", mid);
break;
}
}
if (left >right)
printf("找不到\n");
return 0;
}
下面将其封装成一个函数
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int Bin_search(int arr[], int sz, int k)
{
int left = 0;
int right =sz - 1;
while (left <= right)
{
int mid = (left + right) >> 1;
if (k > arr[mid])
{
left = mid + 1;
}
else if (k < arr[mid])
{
right = mid - 1;
}
else
return mid;
}
return -1;
}
int main()
{
int arr[20] = { 1,2,3,5,7,8,10,14,23,46 };
int sz = sizeof(arr) / sizeof(arr[0]);
int input = 0;
printf("请输入要查找的数字:\n");
scanf("%d", &input);
int ret = Bin_search(arr, sz, input);
if (ret == -1)
{
printf("找不到\n");
}
else
{
printf("找到了,下标是%d\n", ret);
}
return 0;
}