`
tian798648
  • 浏览: 4678 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

二分法查找

阅读更多
package ruantong.test;

import java.util.Arrays;

public class Test1 {
	public static void main(String[] args) {
		// 定义数组
		int[] a = { 0, 15, 14, 22, 28, 35, 98, 109, 44, 12, 9, 78, 67, 56, 54 };
		Arrays.sort(a);//数组排序
		System.out.println(a.length);
		int search = 109;// 所要查找的值
		int index = 0;// 类似于指针的东西,数组下标
		int start = 0;// 查找起始下标
		int end = a.length;// 查找结束下标
		int count = 0;// 保留循环次数
		while (true) {
			count++;//循环次数
			//每次取得剩余的数组下标
			index = start + ((end - start) / 2); 
			if (a[index] < search) {
				start = index;
			} else if (a[index] > search) {
				end = index;
			} else {
				break;
			}
		}
		System.out.println(" 二分法查找,需要比较的次数:" + count);
	}
}


有人发过帖子,但是数组的length-1无法查找最大数。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics