二分查找算法
package com.xmetc.lhg;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author lhg
*
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
int[] arr = new int[10];
int key;
Scanner scanner = new Scanner(System.in);
System.out.println("Please input each array: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("Plese input the key: ");
key = scanner.nextInt();
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
int local = binarySearch(arr, key);
System.out.println(local);
}
/**
* 二分查找
* @param array
* @param key
* @return
*/
public static int binarySearch(int[] array,int key) {
int low = 0;
int high = array.length-1;
while (low <= high) {
int mid = (low+high) / 2;
int midval = array[mid];
if (midval < key) {
low = mid + 1;
}
else if (midval > key) {
high = mid - 1;
}
else {
return mid;
}
}
return -1;
}
}