最最最简单的二分查找

前言

C语言课上老师讲了最简单的二分查找,刚好算法没学几个的本废废(bushi 不会,本着新手就是爱记录的理念记录一下我在课上敲的第一个二分查找程序

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int arr[100000000];

int main() {
int n,num;
cout << "请输入要查找的数组位数:";
cin >> n;
cout << "请输入数组的所有元素:";
for (int i=0; i < n; i++)
cin >> arr[i];
cout << "请输入要查找的数字:";
cin >> num;
int left=0,right=n-1,mid;
bool is_found=false;
while (left <= right && !is_found) {
mid = (left + right) / 2;
if (arr[mid] == num) is_found = true;
else if (arr[mid] > num) right = mid - 1;
else left = mid + 1;
}
if (is_found) cout << "所在位置为" << mid + 1;
else cout << "查无此数";

return 0;
}