在学习编程的过程中,我觉得不止要获得课本的知识,更多的是通过学习技术知识提高解决问题的能力,这样我们才能走在最前方,本文主要讲述Java 二分查找算法 ,更多Java专业知识,广州疯狂java培训官网与你分享;
编程之美在于算法之美,先来看看二分查找的算法:
隐藏条件:二分查找必须是有序的,从小到大,或从大到小的排序才能进行二分查找,下面来看看代码:
package com.cn.daming;
public class MainActivity {
/**
* @param args
*/
public static void main(String[] args) {
int[] aInts = newint[]{1,3,5,8,11,14,16,24,37,47,49,56,63,83,223};
//排序是从小到大
int[] aInts2 = newint[]{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 thereault 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;
}
}
阅读(519) | 评论(0) | 转发(0) |