Java查找算法——二分查找

import java.lang.reflect.Array;
import java.nio.Buffer;
import java.util.Arrays;
import java.util.Random;
class BinarySearch_Find{
private int[] temp;
private int searchKey;
private int lowerBound = 0; //下界
private int upperBound ; //上界
private int curNum;
public int[] getTemp() {
return temp;
}
public void setTemp(int[] temp) {
this.temp = temp;
}
public BinarySearch_Find(int[] temp) {//构造函数
this.temp = temp;
this.upperBound = temp.length-1;
}
public int find(int searchKey){
this.searchKey = searchKey;
while(true){
curNum = (lowerBound+upperBound)/2;
if(temp[curNum]==this.searchKey){
return curNum; //find
}
else if(lowerBound>upperBound){
return -1; //没有find
}
else{
if(temp[curNum]<this.searchKey){
lowerBound = curNum+1;
}
else{
upperBound = curNum-1;
}
}
}
}
}
class RandomArrays{ //生成随机数组,有Num个
public int[] getArrays(int Num){
int[] Arrays = new int[Num];
Random r = new Random();
for(int i=0;i<Num;i++){
Arrays[i] = r.nextInt(1000);
// System.out.print(Arrays[i]+"、");
}
return Arrays;
}
}
class OrderedArrays{ //生成有序数组,从0开始到Num
public int[] getArrays(int Num){
int[] Arrays = new int[Num];
for(int i=0;i<Num;i++){
Arrays[i] = i;
// System.out.print(Arrays[i]+"、");
}
return Arrays;
}
}
public class Binary_Search {
public static void main(String[] args) {
// TODO 自动生成的方法存根
// RandomArrays array_demo = new RandomArrays();
// BinarySearch_Find arrays = new BinarySearch_Find(array_demo.getArrays(100));
OrderedArrays array_demo = new OrderedArrays();
BinarySearch_Find arrays = new BinarySearch_Find(array_demo.getArrays(100));
System.out.println(Arrays.toString(arrays.getTemp()));
System.out.println(arrays.find(1000));
}
}


本文只发表于博客园和tonglin0325的博客,作者:tonglin0325,转载请注明原文链接:https://www.cnblogs.com/tonglin0325/p/5328796.html

浙公网安备 33010602011771号