手机版
你好,游客 登录 注册
背景:
阅读新闻

Java针对数组的普通查找法和二分查找法

[日期:2012-03-20] 来源:Linux社区  作者:jadyer [字体:大 中 小]
下面是针对数组的普通查找法和二分查找法的示例代码
  1. package com.jadyer.sort;  
  2.   
  3. /** 
  4.  * 数组查找方式 
  5.  * @detail 这里演示了普通查找法和二分查找法 
  6.  */  
  7. public class ArraySearch {  
  8.     public static void main(String[] args) {  
  9.         int commonResult = commonSearch(new int[]{1,5,6,7,4,3,9,11,13,14,16,19,21}, 9);  
  10.         int binaryResult = binarySearch(new int[]{1,3,4,6,7,8,9,12,15,17,18,20,22}, 8);  
  11.         System.out.println("二分查找法: " + binaryResult);  
  12.         System.out.println("普通查找法: " + commonResult);  
  13.     }  
  14.       
  15.     /** 
  16.      * 普通查找法 
  17.      * @detail 该方式最好理解,同时效率也最低 
  18.      */  
  19.     public static int commonSearch(int[] array, int value){  
  20.         for(int i=0; i<array.length; i++){  
  21.             if(value == array[i]){  
  22.                 return i; //返回该元素在数组中的下标   
  23.             }  
  24.         }  
  25.         return -1; //不存在该元素则返回-1   
  26.     }  
  27.   
  28.     /** 
  29.      * 二分查找法 
  30.      * @detail 要求数组有序,升序或降序均可 
  31.      */  
  32.     public static int binarySearch(int[] array, int value){  
  33.         int low = 0; //最小元素值的下标   
  34.         int high = array.length - 1; //最大元素值的下标   
  35.         int middle; //中间元素的下标   
  36.         while(low <= high){  
  37.             middle = (low+high) / 2;  
  38.             for(int i=0; i<array.length; i++){  
  39.                 System.out.print(array[i]);  
  40.                 if(i == middle){  
  41.                     System.out.print("#"); //在元素后面用#号标识其为中间元素   
  42.                 }  
  43.                 System.out.print(" "); //各元素间用空格隔开   
  44.             }  
  45.             System.out.println();  
  46.             if(value == array[middle]){  
  47.                 return middle;  
  48.             }  
  49.             if(value < array[middle]){  
  50.                 high = middle - 1; //右侧的不要了   
  51.             }  
  52.             if(value > array[middle]){  
  53.                 low = middle + 1; //左侧的不要了   
  54.             }  
  55.         }  
  56.         return -1; //不存在该元素则返回-1   
  57.     }  
  58. }  
linux
相关资讯       Java教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款