package arrays.compara;
/**
*
* @author Happy 二分查找法
*/
public class BinarySearch {
public static void main(String[] args) {
int[] arrInt = { 2, 34, 32, 24, 23, 34, 12, 3, 4, 2 };
int index = bSearch(29, arrInt, 0, arrInt.length);
System.out.println("Index : " + index);
/*
* for (int i : arrInt) { System.out.println(i); }
*/
}
// js二分查找法(没有成功)
private static int bSerarch(int[] arrInt, int value) {
int startIndex = 0, stopIndex = arrInt.length - 1, middle = (int) (Math
.floor((stopIndex + startIndex) / 2));
while (arrInt[middle] != value && startIndex < stopIndex) {
// adjust search area(调整查找范围)
if (value < arrInt[middle]) {
stopIndex = middle - 1;
} else if (value > arrInt[middle]) {
startIndex = middle + 1;
}
// recalculate middle(重新计算中项索引)
middle = (int) Math.floor((stopIndex + startIndex) / 2);
}
// make sure it's the right value(确保返回正确的值)
return (arrInt[middle] != value) ? -1 : middle;
}
// java二分查找法
private static void bSearch(int[] arrInt, int seek) {
// 要查找的值
// int seek = 33;
// 类似于指针的东西
int index = 0;
// 查找起始下标
int start = 0;
// 查找结束下标
int end = arrInt.length - 1;
// 计数器
int count = 0;
while (true) {
count++;
// 初始化数组中间值的下标
// 原来为index = (start + end) / 2;当start + end的值超过了最大的正int值的时候, index
// 会变成负值,这个时候就会抛出异常