二分查找非递归实现
一 区间左闭右闭
#include<stdio.h>
#include<stdlib.h>
int BinarySerach(int *arr, int x, int sz)
{
int left = 0;
int right = sz - 1;//左闭右闭
while (left <= right)//注意有等号
{
int mid = left + (right - left) / 2;
while(arr[mid] == x)
{
return mid;
}
if (arr[mid]>x)
{
right = mid - 1;//注意是mid-1
}
if (arr[mid]<x)
{
left = mid + 1;
}
}
return -1;
}
int main()
{
int arr[10] = { 1, 3, 5, 6, 7, 9, 11, 12, 14, 48 };
int sz = sizeof(arr) / sizeof(arr[0]);
int ret=BinarySerach(arr, 50, sz);
printf("%d\n", ret);
system("pause");
return 0;
}
二 区间左闭右开
#include<stdio.h>
#include<stdlib.h>
int BinarySerach(int *arr, int x, int sz)
{
int left = 0;
int righ