欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分法查找有序数组中目标值

程序员文章站 2024-03-17 14:52:34
...

二分查找法理论不说了,直接上代码


#include <iostream>
#include<vector>
using namespace std;

int search(vector<int>&nums, int target)
{
	int first = 0;
	int last = nums.size();
	while(first != last)
	{
		int mid = first + (last - first)/2;
		if(nums[mid] == target)return mid;
		if(target > nums[mid])
		{
			first = mid + 1;
		}
		else
		{
			last = mid;
		}
	}
	return -1;
}
int main()
{
	vector<int>test(6, 0);
	test = {0,2,3,4,5};
	int re = search(test, 2);
   cout << re<<endl;
   return 0;
}

以上代码,查找一个升序数组中的值,并返回下标。其输入目标值为2,输出下标为1.

相关标签: C++