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.
}
}
posted @ 2018-04-02 14:24  SessionBest  阅读(96)  评论(0编辑  收藏  举报