# 二分查找递归实现，非递归实现

#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 right = sz;//左闭右开
while (left < right)//注意此处没有等于
{
int mid = left + (right - left) / 2;
if (arr[mid] == x)
{
return mid;
}

if (arr[mid]>x)
{
right = mid ;//注意此处不是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, 9, sz);
printf("%d\n", ret);
system("pause");
return 0;
}

#include<stdio.h>
#include<stdlib.h>
int BinarySerachR(int *arr, int x, int left, int right)
{
while (left <= right)

{
int mid = (right - left) / 2 + left;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
{
return BinarySerachR(arr, x, left, mid - 1);
}
else
{
return BinarySerachR(arr, x, mid + 1, right);
}
}
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=BinarySerachR(arr, 50, 0, sz);
printf("%d\n", ret);
system("pause");
return 0;

}

• 点赞
• 评论 3
• 分享
x

海报分享

扫一扫，分享海报

• 收藏 1
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

daidaihaha

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
03-26 449

04-07 497
05-31 963
01-06 4576
02-19 3172
12-26
02-24 1282
03-26 103
10-10 6312