Vulkan

Cracking The Coding Interview 9.3

//Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order.
//
//EXAMPLE:
//
//Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
//
//Output: 8 (the index of 5 in the array)
#include <iostream>
using namespace std;

//原始二分法
//int search(int *a, int begin, int end,int key)
//{
	//int mid;
	//while(begin < end)
	//{
	//	mid = (begin + end)/2;
	//	if (a[mid] == key)
	//	{
	//		return mid;
	//	}
	//	if (key < a[mid])
	//	{
	//		end = mid;
	//	} 
	//	else
	//	{
	//		begin = mid;
	//	}
	//}

	//if (begin < end)
	//{
	//	int mid = (begin + end)/2;
	//	if (a[mid] == key)
	//	{
	//		return mid;
	//	}
	//	if (key < a[mid])
	//	{
	//		search(a,begin,mid-1,key);
	//	} 
	//	else
	//	{
	//		search(a,mid+1,end,key);
	//	}
	//}
//}

int searchInRotate(int *a, int begin, int end,int key)
{
	
	while(begin < end)
	{
		int mid = (begin + end)/2;
		if (a[mid] == key)
		{
			return mid;
		}

		if (a[mid] >= a[begin])
		{
			if (key < a[mid] && key >= a[begin])
			{
				end = mid-1;
			}
			else
			{
				begin = mid+1;
			}
		}
		else
		{
			if (key > a[mid] && key <a[begin])
			{
				begin = mid + 1;
			} 
			else
			{
				end = mid -1;
			}
		}
	
	}
}


int main()
{
	int a[12] = {15,16,19,20,25,1,3,4,5,7,10,14};
	//int a[12] = {1,3,4,5,7,10,14,15,16,19,20,25};
	//cout<<search(a,0,11,7);
	cout<<searchInRotate(a,0,11,25);
	return 0;
}

posted on 2014-04-28 10:45  Vulkan  阅读(125)  评论(0编辑  收藏  举报

导航