Java针对数组的普通查找法和二分查找法
| [日期:2012-03-20] |
来源:Linux社区
作者:jadyer |
[字体:大 中 小]
|
下面是针对数组的普通查找法和二分查找法的示例代码
- package com.jadyer.sort;
-
-
-
-
-
- public class ArraySearch {
- public static void main(String[] args) {
- int commonResult = commonSearch(new int[]{1,5,6,7,4,3,9,11,13,14,16,19,21}, 9);
- int binaryResult = binarySearch(new int[]{1,3,4,6,7,8,9,12,15,17,18,20,22}, 8);
- System.out.println("二分查找法: " + binaryResult);
- System.out.println("普通查找法: " + commonResult);
- }
-
-
-
-
-
- public static int commonSearch(int[] array, int value){
- for(int i=0; i<array.length; i++){
- if(value == array[i]){
- return i;
- }
- }
- return -1;
- }
-
-
-
-
-
- public static int binarySearch(int[] array, int value){
- int low = 0;
- int high = array.length - 1;
- int middle;
- while(low <= high){
- middle = (low+high) / 2;
- for(int i=0; i<array.length; i++){
- System.out.print(array[i]);
- if(i == middle){
- System.out.print("#");
- }
- System.out.print(" ");
- }
- System.out.println();
- if(value == array[middle]){
- return middle;
- }
- if(value < array[middle]){
- high = middle - 1;
- }
- if(value > array[middle]){
- low = middle + 1;
- }
- }
- return -1;
- }
- }

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