CC150 - 11.3

时间:2022-09-12 19:13:18

Question:

Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order.

 package POJ;

 import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List; public class Main { /**
*
* 11.3 Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an
* element in the array. You may assume that the array was originally sorted in increasing order.
*
*/
public static void main(String[] args) {
Main so = new Main();
int[] list = { 10, 15, 20, 0, 5 };
System.out.println(so.search(list, 0, 4, 5));
} public int search(int[] list, int left, int right, int x) {
int mid = (right + left) / 2;
if (x == list[mid])
return mid;
if (left > right)
return -1;
if (list[left] < list[mid]) {
// left is normally ordered
if (x >= list[left] && x <= list[mid]) {
return search(list, left, mid - 1, x);
} else {
return search(list, mid + 1, right, x);
}
} else if (list[left] > list[mid]) {
// right is normally ordered
if (x >= list[mid] && x <= list[right]) {
return search(list, mid + 1, right, x);
} else {
return search(list, left, mid - 1, x);
}
} else {
// list[left]==list[mid]
// left half is all repeats
if (list[mid] != list[right]) {
return search(list, mid + 1, right, x);
} else {
// search both halves
int result = search(list, left, mid - 1, x);
if (result == -1)
return search(list, mid + 1, right, x);
else
return result;
}
}
}
}