[Java] JAVA 二分查找法 →→→→→进入此内容的聊天室

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

回复 "JAVA 二分查找法"

这儿你可以回复上面这条便签

captcha