编程之美在于算法之美,先来看看二分查找的算法:
隐藏条件:二分查找必须是有序的,从小到大,或从大到小的排序才能进行二分查找,下面来看看代码:
package com.cn.daming;
public class MainActivity {
/**
* @param args
*/
public static void main(String[] args) {
int[] aInts = new int[]{1,3,5,8,11,14,16,24,37,47,49,56,63,83,223}; //排序是从小到大
int[] aInts2 = new int[]{322,243,211,156,98,85,79,68,53,47,38,24,13,6,2}; //排序是从大到小
// TODO Auto-generated method stub
MainActivity main = new MainActivity();
System.out.println("aInts the reault is : " + main.binarySearch(aInts, 0, aInts.length, 24));
System.out.println("aInts2 the reault is : " + main.binarySearch2(aInts2, 0, aInts2.length, 243));
}
//从小到大的二分查找
private int binarySearch(int[] a, int start, int len, int key) {
int high = start + len, low = start - 1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (a[guess] < key)
low = guess;
else
high = guess;
}
if (high == start + len)
return ~(start + len);
else if (a[high] == key)
return high;
else
return ~high;
}
//从大到小的二分查找
private int binarySearch2(int[] a, int start, int len, int key) {
int high = start + len, low = start - 1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (a[guess] > key)
low = guess;
else
high = guess;
}
if (high == start + len)
return ~(start + len);
else if (a[high] == key)
return high;
else
return ~high;
}
}
返回值就是返回要查的key的下标;
看结果如图: