二分搜索法

二分搜索法(C++)

//
//Description:二分搜索法
//
#include <iostream>
using namespace std;

int binarySearch(int a[], int x, int n);//函数声明

void main()
{
	cout << "\n-----------------二分搜索法----------\n";
 	int n=0;
	cout << "enter the values of n:\n";
	cin >> n;
	int b[6];//  *注意数组的初始化
	cout << "please enter the values of b[" << n << "](from small to big )\n";
	for (int j = 0; j<n; j++)
	{
		cin >> b[j];
	}
	for (int p = 0; p<n; p++)
	{
		cout << b[p] << "\t";
	}
	cout << endl;
	cout << "enter the the value of which you want to search:\n";

	int x;
	cin >> x;

	int e = binarySearch(b, x, n) + 1;//函数调用      注意数组的调用
	cout << e << endl;
}

int binarySearch(int a[], int x, int n)//函数定义
{
	//在依大小次序排的数组a[n]中检索x,找到时返回它的位置
	int left = 0; int right = n - 1;
	while (left <= right)
	{
		int middle = (left + right) / 2;
		if (x == a[middle]) return middle;
		if (x>a[middle]) left = middle + 1;
		else right = middle - 1;
	}
	return -1;
}

你可能感兴趣的:(c,search)