您的位置:首页 > 其它

[源码]排序数组二分法(折半)查找

2013-03-08 16:25 253 查看
对于已排序的数组,二分法是一种很简单、有效的查找方式,算法复杂度为O(log2n);

代码:

package alg;

public class Bisection {

	public static int bisectionSearch(int value,int[] array) {
		int minIndex = 0;
		int curIndex = 0;
		int maxIndex = array.length - 1;
		int count = 0;	// 用于循环次数记数
		int result = -1;
		
		if (value == array[maxIndex]) {
			result = maxIndex;
		} else if (value == array[minIndex]) {
			result = minIndex;
		} else {
			while(true) {
				// 如果两者相同或相邻,由于二者的值(除首次)均来自于已与value比较不等的值,因此数组中没有该值。
				if (2 > maxIndex - minIndex) {
					result = -1;
					break;
				}
				curIndex = minIndex + (maxIndex - minIndex) / 2;
				if (array[curIndex] == value) {
					result = curIndex;
					break;
				} else if (array[curIndex] < value) {
					minIndex = curIndex;
				} else {
					maxIndex = curIndex;
				}
				count++;
			}
		}
		System.out.println("loops = " + count);
		return result;
	}
	
	public static void main(String[] args) {
		int num = 1000;
		int value = 0;
		int[] array = new int[num];
		for (int i = 0; i < num; i++) {
			array[i] = i;
		}
		System.out.println("value = " + value + " at index " + bisectionSearch(value,array) + " of array.");
	}
}
Author:Pirate Leo

blog:http://blog.csdn.net/pirateleo

email:codeevoship@gmail.com

转载请注明出处,谢谢。

由于文中在发布后难免会有勘误或补充,推荐到本博客中阅读本文。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐