1.折半查找算法
折半查找(Binary Search)又称二分查找,其要求数据序列呈线性结构,也就是经过排序的数据序列。对于没有排序的数据序列,要先对其进行排序。
折半查找是一种递归过程,每次折半查找一次,可使查找范围缩小一半,当查找范围缩小到只有一个数据时,而该数据仍与关键字不相等,说明查找失败。
2.java代码的折半查找算法实现
public class BinarySearch {
public int doSearch(int[] array,int data){
int result = -1;
int mid,low,hight;
low = 0;
hight = array.length - 1;
while(low < hight){
mid = (low + hight)/2;
if(array[mid] == data){
result = mid;
return result;
}else if(array[mid] > data){
hight = mid -1;
}else if(array[mid] < data){
low = mid + 1;
}
}
return result;
}
}
public class SearchDemo {
private static final int size = 75;
private static final int data = 120;
public static void main(String[] args) {
// TODO Auto-generated method stub
testBinarySearch();
}
private static void testBinarySearch() {
// TODO Auto-generated method stub
int[] array = new int[size];
for(int i=0;i<size;i++){
array[i] = (int)(100+Math.random()*(100+1));
}
BubbleSort bubbleSort = new BubbleSort();
array = bubbleSort.doSort(array);
System.out.print("数组为:\n");
for(int k=0;k<array.length;k++){
System.out.print(" "+array[k]);
if((k+1) % 10 == 0){
System.out.print("\n");
}
}
System.out.print("\n");
BinarySearch binarySearch = new BinarySearch();
int result = binarySearch.doSearch(array,data);
if(result == -1){
System.out.print("在数组中没有找到:"+data);
}else{
System.out.print("数据:"+data+" 位于数组中的:"+(result+1)+"位");
}
}
}
3.程序结果
数组为:
102 102 103 103 104 106 107 108 108 110
110 111 111 120 121 122 124 124 127 130
132 132 134 135 138 139 139 140 140 142
143 143 144 146 150 152 152 153 154 155
156 160 162 162 162 167 167 169 172 172
173 174 177 177 179 179 181 182 182 183
184 186 188 191 191 191 193 194 194 195
195 195 196 200 200
数据:120 位于数组中的:14位