c_cpp 二进制搜索

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 二进制搜索相关的知识,希望对你有一定的参考价值。

/*
http://ideone.com/FTNZKp
*/

#include <iostream>
using namespace std;

int BinarySearch(int a[], int l, int r, int item){
	int mid = l + (r - l) / 2;
	if(l <= r){
		if(item == a[mid])
			return mid;
		else if(item < a[mid])
			return BinarySearch(a, l, mid-1, item);
		else
			return BinarySearch(a, mid+1, r, item);
	}
	else
	return -1;
}
int main() {
	// your code goes here
	int a[] = {1, 5, 9 , 10, 45, 48, 95, 100};
	int len = sizeof(a)/sizeof(a[0]);
	int item = 95;
	int index =  BinarySearch(a, 0, len, item);
	if(index == -1)
		cout << "Item " << item << " not found!" <<endl;
	else
		cout << "Item " << item << " found at index : " << index << endl;
	return 0;
}
/*
http://ideone.com/RqdJ4b
*/

#include <iostream>
using namespace std;

int BinarySearch(int a[], int len, int item){
	int l = 0, r = len-1;
	while(l <= r){
		int mid = l + (r -l) / 2;
		if(item == a[mid])
			return mid;
		else if(item < a[mid]){
			r = mid -1;
		}
		else
			l = mid + 1;
	}
	return -1;
}
int main() {
	// your code goes here
	int a[] = {1, 5, 9 , 10, 45, 48, 95, 100};
	int len = sizeof(a)/sizeof(a[0]);
	int item = 100;
	int index =  BinarySearch(a, len, item);
	if(index == -1)
		cout << "Item " << item << " not found!" <<endl;
	else
		cout << "Item " << item << " found at index : " << index << endl;
	return 0;
}

以上是关于c_cpp 二进制搜索的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 二进制搜索

c_cpp 二进制搜索

c_cpp 二进制搜索

c_cpp 二进制搜索模板

c_cpp 矩阵二进制搜索

c_cpp 二进制数组搜索