JAVA 二分法

 

代码
 1 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,123753677189122290435555888110411112222,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 
67 

 

 

posted @ 2010-12-08 21:21  X-Jonney  阅读(1020)  评论(0)    收藏  举报