Cracking the coding interview--Q9.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)

译文:

给一个长度为n的有序整型数组,但它已经被旋转了未知次,给一个O(log n)的算法在这个数组中找出一个元素,你可以假设这个数组的初始排列是增序的。

例如:

输入:在数组(15 16 19 20 25 1 3 4 5 7 10 14)中找出5

输出:8(5在数组中的下标为8)

解答

首先要理解这个数组是有序的,但被旋转过了,也就是说,数组部分是有序的;然后题目要求是O(log n)的算法,显然可以用到二分查找法,但数组部分有序,即前面一段有序,后面一段有序,且前面那段的数要大于等于后面那段的数(本题递增序列),所以首先需要判断a[mid]是落在前半段还是后半段假如a[mid]落在前半段(即a[mid]>=a[low]),这时如果所求值value是位于a[low]和a[mid]之间,则更新high = mid - 1;否则更新low = mid + 1。假如a[mid]落在后半段 (即a[mid]<a[low]),这时如果x的值是位于a[mid]和a[low]之间,则更新low = mid + 1;否则更新high = mid - 1,代码如下:

class Q9_3{
	public static int search(int[] a,int fromIndex,int toIndex,int value){
		int low=fromIndex;
		int high=toIndex-1;
		while(low<=high){
			int mid=(low+high)>>>1;
		/*	int midVal=a[mid];
			if(a[low]<value){
				if(midVal>value)
					high=mid-1;
				else if(midVal<)
			}*/
			if(a[mid]==value) return mid;
			if(a[mid]>=a[low]){
				if(value<a[mid]&&value>=a[low])
					high=mid-1;
				else
					low=mid+1;
			}else{
				if(value<=a[high]&&value>a[mid])
					low=mid+1;
				else
					high=mid-1;
			}
		}
		return -1;
	}
	public static void main(String[] args){
		int[] a={
        	15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14
    	};
    	System.out.println(search(a,0,12,5));
	}
}

---EOF---


你可能感兴趣的:(Cracking the coding interview--Q9.3)