binary search in sorted array:
package me.util.algorithm;
/**
* binary search util
* @author eric
* @date 2010-8-29 下午07:09:41
*/
public class BinarySearchUitl {
public static void main(String[] args) {
int[] is = new int[] { -10, -9, -9, -5, -4, -3, -3, -2, -1, 0, 1, 2, 5, 6, 7, 8, 9, 11, 14 };
System.out.println(locateNumInSortedArray(-5, is));
System.out.println(locateNumInSortedArray(4, is));
}
/**
* locate num in a sorted array
* @param num number to locate
* @param arr sorted array in asc order
* @return index of the num in array.If not find,-1 will be return.
*/
public static int locateNumInSortedArray(int num, int[] arr) {
if (arr.length == 0 || arr[0] > num || arr[arr.length - 1] < num) {
return -1;
}
int startIndex = 0, endIndex = arr.length - 1;
while (startIndex <= endIndex) {
int middleIndex = (startIndex + endIndex) >> 1;
if (num == arr[middleIndex]) {
return middleIndex;
} else if (num > arr[middleIndex]) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
return -1;
}
}