Skip to content

Commit 9b4e724

Browse files
committed
20190401
1 parent 74af0c6 commit 9b4e724

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

二分搜索(分治示例).cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// 贾立威 201710405130
2+
#include <iostream>
3+
#include <algorithm>
4+
5+
using namespace std;
6+
const int maxn = 105;
7+
int a[maxn];
8+
9+
void _bsearch(int l, int r, int c) {
10+
int m = l + (r - l) / 2;
11+
if (l == r - 1 && a[l] != c && a[r] != c) {
12+
cout << "数据没有找到!" << endl;
13+
cout << "查找边界为第" << l + 1 << "个元素和第" << r + 1 << "个元素" << endl;
14+
return;
15+
}
16+
17+
if (a[m] == c) {
18+
cout << "查找的数据为数组中第" << m + 1 << "个元素" << endl;
19+
return;
20+
} else if (a[m] < c) {
21+
_bsearch(m, r, c);
22+
} else if (a[m] > c) {
23+
_bsearch(l, m, c);
24+
}
25+
}
26+
27+
int main() {
28+
int n, c;
29+
cout << "请输入待查找有序数组大小: ";
30+
cin >> n;
31+
cout << "请逐个输入待查找有序数组的元素:" << endl;
32+
for (size_t i = 0; i < n; i++) {
33+
cin >> a[i];
34+
}
35+
sort(a, a + n);
36+
cout << "请输入要查找的数据:";
37+
cin >> c;
38+
_bsearch(0, n, c);
39+
system("pause");
40+
return 0;
41+
}

0 commit comments

Comments
 (0)