package com.wf.bean;
public class J {
/**
* 二分查找
*/
public static void main(String[] args) {
int arr[] = { 11, 22, 33, 44, 55, 66, 77 };
System.out.println(getIndex(arr, 66));
System.out.println(getsearch(arr, 55));
}
public static int getIndex(int arr[], int value) {
int min = 0;
int max = arr.length - 1;
int mid = (min + max) / 2;
while (arr[mid] != value) {
if (arr[mid] < value) {
min = mid + 1;
} else if (arr[min] > value) {
max = mid - 1;
}
if (arr[min] > arr[max]) {
return -1;
}
mid = (min + max) / 2;
}
return mid;
}
public static int getsearch(int arr[], int key) {
int min = 0, max = arr.length - 1;
while (min <= max) {
int mid = (min + max) / 2;
if (key > arr[mid]) {
min = mid + 1;
} else if (key < arr[mid]) {
max = mid - 1;
} else {
return mid;
}
}
return -1;
}
}
|
|