有序数组的二分搜索/二分查找
其实这个二分算法在Collections集合工具类中有实现,没有改动直接就拿来了。
Collections.java中实现的二分查找算法
Searches the specified list for the specified object using the binary search algorithm.
使用二分查找搜索特定的元素,list集合必须是有序的。
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
}
return -(low + 1); // key not found
}
贴代码:
package sort;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: ASUS
* Date: 14-9-11
* Time: 上午12:58
* To change this template use File | Settings | File Templates.
*/
public class BinarySearchTest {
public static <T extends Comparable<? super T>> int binarySearch(T[] arr, T key) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
Comparable<? super T> midVal = arr[mid];
int cmp = midVal.compareTo(key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
public static void main(String args[]) {
Integer[] arr = {1, 2, 9, 6, 4, 3, 54, 7};
Arrays.sort(arr);
for (int i : arr) {
System.out.println(i);
}
//二分查找的数组必须在有序数组中进行
System.out.println(binarySearch(arr, 9)); //9这个元素在排好序的数组中索引为6
}
}
==========END==========