JAVA 二分查找

package com.session.chop;

import java.util.Arrays;

/**
* 二分查找
*/
public class BinarySearch {
public static void main(String[] args) {
int[] array = new int[]{1, 24, 3, 9, 5, 6, 4, 8};
Arrays.sort(array);
System.out.println(binarySearch0(array, 0, 8, 4));
}



private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex;
int high = toIndex - 1;

while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];

if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
}
原文地址:https://www.cnblogs.com/sessionbest/p/8692983.html