二分查找的java实现
原理:
二分查找是在一个有序表(数据是按其值由小到大或由大到小依次存放的,这里我们以值由小到大排列为例)中,每次都与中间的那个元素比较,若相等则查找成功;否则,调整查找范围,若中间那个元素的值小于待查值,则在表的后一半中查找;若中间那个元素的值大于待查值,则在表的前一半中查找;如此循环,每次只与一半中的一个元素比较,可使查找效率大大提高。
JAVA实现:
1 import java.util.Arrays;
2
3 /**
4 * This program show how to search a value in a array with binary_search method.
5 * @author hewenwu
6 * @version 2014/4/19
7 * */
8
9 public class BinarySearch {
10
11 public static void main(String[] args) {
12
13 int[] source_array = new int[100];
14
15 //给数组随机赋值
16 for(int i=0;i<100;i++) {
17
18 source_array[i] = (int)( Math.random()*100 );
19
20 }
21
22 int value = source_array[1];//要查找的value
23
24 //二分查找要求数组是有序的,所以先把数组排序,这里就直接调用java内置的排序算法
25
26 Arrays.sort(source_array);
27
28 //打印排序后的数组
29 for(int i=0;i<source_array.length;i++) {
30
31 System.out.println(source_array[i]);
32 }
33
34 //打印查找的结果
35 if(binary_search1(source_array,value)==-1) {
36
37 System.out.println("数组中没有该元素!");
38
39 }else {
40
41 System.out.println(value+"在source_array中的第"+(binary_search1(source_array,value)+1)+"个位置");
42
43 }
44
45
46
47 if(binary_search2(source_array,0,99,value)==-1) {
48
49 System.out.println("数组中没有该元素!");
50
51 }else {
52
53 System.out.println(value+"在source_array中的第"+(binary_search2(source_array,0,99,value)+1)+"个位置");
54
55 }
56 }
57
58 //二分查找算法1
59
60 public static int binary_search1(int[] source,int value) {
61
62 int start = 0;//数组的第一个元素的下标
63 int end = source.length-1;//数组的最后一个元素的下标
64
65 while(start<=end) {
66
67 int middle = (start+end)/2;//数组中间元素的下标
68
69 if(source[middle] == value) {
70
71 return middle;
72
73 }else if(value < source[middle]) {
74
75 end = middle-1;
76
77 }else {
78
79 start = middle+1;
80 }
81 }
82
83 return -1; //没有找到返回-1
84
85 }
86
87
88 //在数组某个特定部分查找元素
89 public static int binary_search2(int[] source,int start,int end,int value) {
90
91 int middle = (start + end)/2;
92
93 if(value>source[end]||value<source[start]||start>end) {
94
95 return -1;
96
97 }
98
99 if(value<source[middle]) {
100
101 return binary_search2(source,start,middle-1,value);
102
103 }else if(value>source[middle]){
104
105 return binary_search2(source,middle+1,end,value);
106
107 }else {
108
109 return middle;
110
111 }
112
113 }
114
115
116 }