# 二分查找

2 篇文章 0 订阅

## 1.递归写法

//二分查找的递归写法
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100];
void HalfSreach(int begin, int end, int key) {
if (begin >= end) {//递归结束条件
cout << "-1" << endl;
exit(0);
}
int mid = (begin+end) / 2;
if (a[mid] == key) {
cout << mid << endl;
exit(0);
} else if (a[mid] > key) {
HalfSreach(begin, end-1, key);
} else {
HalfSreach(mid+1, end, key);
}
}
int main() {
int N, n;
cin >> N;
memset(a, 0, sizeof(int));
for (int i = 0; i < N; ++i) cin >> a[i];
sort(a, a+N);
cin >> n;
HalfSreach(0, N, n);
}

## 2.非递归写法

//二分查找的非递归写法
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100];
void HalfSreach(int begin, int end, int key) {
while (begin <= end) {
int mid = (begin+end) / 2;
if (a[mid] == key) {
cout << mid << endl;
exit(0);
} else if (a[mid] > key) {
end = mid-1;
} else {
begin = mid+1;
}
}
}
int main() {
int N, n;
cin >> N;
memset(a, 0, sizeof(int));
for (int i = 0; i < N; ++i) cin >> a[i];
sort(a, a+N);
cin >> n;
HalfSreach(0, N, n);
}
• 1
点赞
• 7
评论
• 24
收藏
• 一键三连
• 扫一扫，分享海报

05-08 302
10-07 2万+

07-31 690
12-06 628
03-20 112
01-02 48