1.python实现
from math import floor
arr = [1, 2, 3, 4, 5, 6, 8, 9, 10, 11]
left = 0
right = len(arr)-1
res = 7
while (left <= right):
mid = floor((left + right)/2)
if (arr[mid] < res):
left = mid + 1
elif (arr[mid] > res):
right = mid - 1
else:
print(f'找到了,下标为{mid}')
break
if (left > right):
print('找不到')
2.c语言实现
#include <stdio.h>
int main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 8, 9, 10, 11};
int res = 8;
int rz = sizeof(arr) / sizeof(arr[0]);
int left = 0;
int right = rz - 1;
int mid = (rz - 1 + 0) / 2;
while (left <= right)
{
mid = (left + right) / 2;
if (arr[mid] < res)
{
left = mid + 1;
}
else if (arr[mid] > res)
{
right = mid - 1;
}
else
{
printf("找到了,下标为:%d\n", mid);
break;
}
}
if (left > right)
printf("找不到\n");
return 0;
}
标签:arr,right,int,demo,mid,二分法,res,left
From: https://www.cnblogs.com/hikk/p/17678193.html