# 错误写法示例

## 1.第一种写法

``````public static int bs1(int a[], int x, int n) {
int left = 0;
int right = n - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (x == a[middle])
return middle;
if (x > a[middle])
left = middle;
else
right = middle;
}
return -1;
}``````

## 2.第一种写法评析

[x] 是错误的

``````Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at bin_search.Demo1.main(Demo1.java:21)``````

## 3.第二种写法

``````public static int bs2(int a[], int x, int n) {
int left = 0;
int right = n - 1;
while (left < right -1) {
int middle = (left + right) / 2;
if (x < a[middle])
right = middle;
else
left = middle;
}
if (x == a[left]) return left;
return -1;
}``````

[x] 是错误的

# 正确写法

``````public static <T>
int binarySearch(List<? extends Comparable<? super T>> list, T key) {
if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
return Collections.indexedBinarySearch(list, key);
else
return Collections.iteratorBinarySearch(list, key);
}

private static <T>
int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {
int low = 0;
int high = list.size()-1;

while (low <= high) {
int mid = (low + high) >>> 1;
Comparable<? super T> midVal = list.get(mid);
int cmp = midVal.compareTo(key);

if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
}

private static <T>
int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key) {
int low = 0;
int high = list.size()-1;
ListIterator<? extends Comparable<? super T>> i = list.listIterator();

while (low <= high) {
int mid = (low + high) >>> 1;
Comparable<? super T> midVal = get(i, mid);
int cmp = midVal.compareTo(key);

if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
}``````

# 总结

1. 数组一定记得要先排序！！！（不排序会出现各种莫名其妙的返回值）
2. 取中位值的时候，需要注意整数加法是否会溢出的问题。
3. 当查找不在数组内的元素时，需要返回-1代表没有找到。
4. 如果出现待查找元素有重复的元素，需要确定返回的是哪一个元素的下标。