用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

JAVA 二分查找法

2015-04-04 作者: java源代码大全举报

[java]代码库

import java.util.*;  
 2 /**
 3 * 
 4 * 一个二分查找法
 5 * @author nileader
 6 */
 7 public class BinaryQuery {  
 8     /**  
 9      *   *折半查找法,又称十分法查找  查找的对象是一个按序排好的数组     
10      */ 
11     public static void main(String[] args) {  
12         int[] initVals = { 9,12, 37, 53, 67, 71, 89, 122, 290, 435, 555, 888, 1104, 1111, 2222,3333,21343,43256,56778300 };  
13         for(int i = 0; i < initVals.length; i++)  
14         {  
15             System.out.print(initVals[i] + "、");  
16         }  
17         Scanner cin = new Scanner(System.in);  
18         while(cin.hasNext())  
19         {  
20             int targetVal = cin.nextInt();  
21             BinaryQuery bq = new BinaryQuery();  
22             int postion = bq.query(initVals,targetVal);  
23             if(postion == -1) System.out.println("没有找到");  
24             else System.out.println("要查找的数字在数组中的第 " + (postion + 1) + "个位置");  
25         }  
26     }  
27 
28     /*  
29      * @param values 要找的数组对象  
30      * @param targetVal 要找的目标数字  
31      * @return -1 没有找到,返回-1  
32      */ 
33     public int query(int[] initVals, int targetVal) {  
34         int lowBound = 0;  
35         int upBound = initVals.length - 1;  
36 
37         //相当于一个指针,指向下一个要比的数字  
38         int nowPostion;  
39 
40         while (true) {  
41 
42             //指向现在所有数字的中间,没有整除时向下取整,如7/2=3  
43             nowPostion = (lowBound + upBound) / 2;  
44             //如果现在这个数字就是了,返回现在的编号  
45             if (initVals[nowPostion] == targetVal) {  
46                 return nowPostion;  
47             }   
48             //如果上界小于下界时,说明已经找完全部了,返回-1表示没有找到  
49             else if (lowBound > upBound) {  
50                 return -1;  
51             }  
52             //还可以继续找  
53             else {  
54                 //当前指针的数比targetVal要小,那么要往小的方向继续找  
55                 if (initVals[nowPostion] < targetVal) {  
56                     lowBound = nowPostion + 1;  
57                 }   
58                 //当前指针的数比targetVal要大,那么要往大的方向继续找  
59                 else {  
60                     upBound = nowPostion - 1;  
61                 }  
62             }  
63         }  
64 
65     }  
66 } //源代码片段来自云代码http://yuncode.net
			


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...