001-Java杂记之二分查找

来源:互联网 发布:土豆for mac 编辑:程序博客网 时间:2024/06/07 13:16

/**
 * 简单的二分查找类
 */
public class BinarySearch {
private static int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

public static void main(String[] args) {
System.out.println(binarySearchIndex(0, myArray.length, 5));
}

/**
  * 二分查找该值的下标
  */
private static int binarySearchIndex(int startIndex, int endIndex, int value) {
int middle = (startIndex + endIndex) / 2;

while(startIndex < endIndex && (!(myArray[middle] == value))) {
if(myArray[middle] < value) {
startIndex = middle + 1;
}else {
endIndex = middle - 1;
}

middle = (startIndex + endIndex) / 2;
}

return myArray[middle] == value ? middle : -1;
}
}

原创粉丝点击