tonglin0325的个人主页

Java递归算法——二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.lang.reflect.Array;
import java.nio.Buffer;
import java.util.Arrays;
import java.util.Random;

class Rec_Find{
private int[] temp;
private int searchKey;
//private int lowerBound = 0; //下界
//private int upperBound ; //上界
private int nElement;

public int[] getTemp() {
return temp;
}

public void setTemp(int[] temp) {
this.temp = temp;
}

public Rec_Find(int[] temp) {//构造函数
this.temp = temp;
//this.upperBound = temp.length-1;
}

public int find(int searchKey,int lowerBound,int upperBound){
int curNum;
this.searchKey = searchKey;
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){
return find(searchKey,curNum+1,upperBound);
}
else{
return find(searchKey,lowerBound,curNum-1);
}
}
}
}

class RandomArray{ //生成随机数组,有Num个

private int[] Arrays;

public int[] getArrays(int Num){
// int[] Arrays = new int[Num];
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 OrderedArray{ //生成有序数组,从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 RecFind {

public static void main(String[] args) {

// RandomArrays array_demo = new RandomArrays();
// BinarySearch_Find arrays = new BinarySearch_Find(array_demo.getArrays(100));

OrderedArray array_demo = new OrderedArray();
Rec_Find arrays = new Rec_Find(array_demo.getArrays(100));
System.out.println(Arrays.toString(arrays.getTemp()));
System.out.println(arrays.find(55,0,100));
}
}