Beijing Institute of Technology on a machine problem - binary search

Beijing Institute of Technology on a machine problem - binary search

Description Title:
binary search {-36, -25,0,12,14,29,35,47,76,100}, the above-mentioned number of binary search ten
test:
Please input data to look for: 14 14 the number 5, a number of times to find
data enter looking for: -25-25 is a second number, the number is 2 to find
the data to find the enter: 121 lookup failed

Also known as binary search binary search, binary search related to introduced: binary search

#include<iostream>
using namespace std;
void search(int num[], int n, int searchNum) {
	int count = 0;
	int first = 0, end = n - 1;
	bool find = false;
	int mid;
	while (first <= end && !find) {
		count++;
		mid = (first + end) / 2;
		if (searchNum == num[mid]) {
			find = true;
			break;
		}
		else if (searchNum < num[mid]) {
			end = mid - 1;
		}
		else {
			first = mid + 1;
		}
	}
	if (find) {
		cout << searchNum << "是第" << mid + 1 << "个数,查找次数为" << count << endl;
	}
	else
		cout << "查找失败" << endl;
}
int main() {
	int num[10] = { -36,-25,0,12,14,29,35,47,76,100 };
	int searchNum;
	int count = 3;
	while (count) {
		cout << "输入要查找的数据:";
		cin >> searchNum;
		search(num, 10, searchNum);
		count--;
	}
	return 0;
}

Run the test results:
Here Insert Picture Description

Published 50 original articles · won praise 50 · views 2937

Guess you like

Origin blog.csdn.net/weixin_45295612/article/details/105385133