【leetcode】【数据结构】 二分查找法

版权声明:来自 T2777 ,请访问 https://blog.csdn.net/T2777 一起交流进步吧 https://blog.csdn.net/T2777/article/details/86761851

上次刷LeetCode提到了二分查找法,但是最后没有用二分法实现,二分查找法是非常基础的算法,也比较容易掌握,这里对二分法进行一些总结。

二分法一般要求这几点

1. 已经排好序应当没有重复值,当有重复值时,下面的算法会出错误    2. 对一道复杂度为O( n )的题目进行优化,而二分法可以将时间复杂度降至 O( log n)  3.一般是找某个位置或某个数,如果是想插入一个,仅仅靠二分法不太现实,毕竟它叫二分查找法,当然实现插入手段当然可以找到。 4. 还有就是小数的问题,要是 (low + high) / 2 得到的是一个小数,显然要进行取整操作,而因为mid本来就是int型的,所以完成 (low + high) / 2 得到的就是一个整数,向下取整。

下面看具体的实现过程,代码中的测试结果是可以进行修改的,可移植:

#include <iostream>
using namespace std;

//c++中没有提供获取数组长度的函数,只有字符串可以strlen可以!!
int binary_search(int a[], int low, int high, int target)
{
	int mid;
	//判断呢需要加上 = 号,否则会出现错误
	while (low <= high)
	{
		mid = (low + high) / 2;
		if (a[mid] == target)
			return mid;
		else if (a[mid] < target)
			low = mid + 1;
		else if(a[mid] > target)
			high = mid - 1;
	}
	cout << "none" << endl;
	return -1;

}

int main()
{
	int a[] = { 1,2,3,4,5,6,7,8,9 };
	int target,res;
	cout << "please enter the target number: " << endl;
	cin >> target;
	res = binary_search(a,0,8,target);
	cout << "the index of the target is: " << res << endl;
	return 0;
}

运行结果1: 

运行结果2:

猜你喜欢

转载自blog.csdn.net/T2777/article/details/86761851