从多次循环移位后的数组中找出特定的元素

给定有n个元素的数组,将其循环移位多次,给定一个时间复杂度为O(log n) 的算法找出特定的元素。

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. 


A为所给的非递减数组。数组下标的最小和最大值为l u。x是要查找的元素。

数组A进行循环移位后一般情况下产生了两个非递减的序列。

具体如下图:



搜索元素由于是两个非递减子序列,所以可以采用二分搜索。

不过搜索时要注意先判断A[mid]在哪个子序列中。再针对不同的情况进行分析。注意:两个子序列相遇处未知。


SOLUTION

Assumptions:
A is the array. l and u are lower and upper indexes of the array. x is the key that we want to
search.
We can do this with a modification of binary search.
int search(int a[], int l, int u, int x) {
	while (l <= u) {
		int m = (l + u) / 2;
		if (x == a[m]) {
			return m;
		} else if (a[l] <= a[m]) {
			if (x > a[m]) {
				l=m+1;
			} else if (x >=a [l]) {
				u = m-1;
			} else {
				l = m+1;
			}
		}
		else if (x < a[m]) u = m-1;
		else if (x <= a[u]) l = m+1;
		else u = m-1;
	}
	return -1;
}


NOTE: What about duplicates? You may observe that the above function doesn’t
give you an efficient result in case of duplicate elements. However, if your array
has duplicate entries then we can’t do better than O(n) which is as good as linear
search.
For example, if the array is [2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2], there is no way to find element
3 until you do linear search.

你可能感兴趣的:(从多次循环移位后的数组中找出特定的元素)