从排序的旋转数组中找原开始元素

给定一个排序数组,经过旋转,找出原起始元素。

Given a sorted list but it is rotated. Find the start point in that list

由于数组使排好序的,但是从第k个元素开始记过了旋转。所以可以使用二分查找来找到起始元素,假设为最小元素。

Hey folks. I think you are all missing a very important hint that the array is sorted and rotated by some K positions. In that case we should use the binary search principle to find the reset point, which will be the minimum element in the array. Below is the complete code to demonstarte this technique that runs in O(Log N) time:

int find_reset_point(int arr[],int start ,int end)
{
	if (start>end)
	{
		return -1;
	}
	int midd;
	while (start<end)
	{
		
		if (end - start <= 1)
		{
			if (arr[start]>arr[end])
			{
				return arr[end];
			}
		}
		midd = (start+end)>>1;
		if (arr[midd]>arr[start])//从中间元素开始考查,如果中间元素大于start元素,表面要搜索的点在midd到end之间
		{
			start = midd;
		}
		else//否则要搜索的点start到midd之间
			end = midd;
	}
	return -1;
}


你可能感兴趣的:(从排序的旋转数组中找原开始元素)