查找算法代码实现

二分搜索

#include <iostream>
using namespace std;

int binarySearch(int arr[], int length,int n) {
	int left = 0;
	int right = length - 1;
	while (left<=right) {
		int mid = left+(right-left) / 2;
		if (arr[mid] == n) {
			return mid;
		}
		else if (arr[mid] > n) {
			right = mid - 1;
		}
		else {
			left = mid + 1;
		}
	}
}
int main(){
	int  arr[9] = { 1,2,5,6,8,9 ,10,11,12};
	int length = sizeof(arr) / sizeof(arr[0]);
	int res=binarySearch(arr,length,5);
	cout << res << endl;
	system("pause");
}

 

点赞