(旋轉陣列問題)給定一個整數型別的迴圈有序陣列,求迴圈陣列的特定值,使用二分查詢法(JAVA實現)
阿新 • • 發佈:2019-01-04
問題:請實現以下函式int indexOf(int [] array ,int key) ,給定一個迴圈有序的陣列,請在這個陣列中找到指定元素,找到的話返回下標,沒找到返回-1。:
解決:首先,使用二分查詢找到陣列的 “臨界點”,臨界點滿足兩個情況:
1. array[left] < array[mid]
2. array[left] <= array[mid]
只有確定分界點,確定了key的範圍,才能找到key的位置.
程式碼塊
public class BinaryFindCycleArr {
public static int FindCycleArr(int[] arr,int key){
int left = 0;
int right = arr.length-1;
while (left <= right) {
int mid = (left + right)/2;
if (key == arr[mid]) {
return mid;
}
if (arr[left] <= arr[mid]) {
if (key < arr[mid] && key >= arr[left]) {
right = mid-1;
}else {
left = mid+1;
}
}else if (arr[left] > arr[mid]) {
if (key < arr[left] && key > arr[mid]) {
left = mid + 1;
}else {
right= mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = new int[]{23,34,41,52,4,8,13,20};
for (int i = 0; i < arr.length; i++) {
int out =FindCycleArr(arr,arr[i]);
System.out.println(out);
}
}
問題延伸:如果限制只找到最大值,程式碼如下:
public static int FindMax(int[] arr){
int left = 0;
int right = arr.length-1;
int max = arr[0];
while (left <= right) {
int mid = (left + right)/2;
if (max >arr[mid]) {
right = right-1;
}else {
max=arr[mid];
left = mid+1;
}
}
return max;
}
…