-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
97 lines (84 loc) · 2.38 KB
/
BinarySearch.java
File metadata and controls
97 lines (84 loc) · 2.38 KB
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
91
92
93
import recursive.BinarySearch;
/**
* Write a description of class BinarySearch here.
*
* @author Sofie Budman
* Period 5
*/
public class BinarySearch
{
private int min;
private int max;
/**
* Constructor for objects of class BinarySearch
* Precondition: max > min
* Postcondition: answer is set with a random number from min to max (exclusive of max)
*/
public BinarySearch(int min, int max)
{
this.min = min;
this.max = max;
}
/**
* doBinarySearch
*
*
* @return : the number of guesses performed before finding the answer
* Precondition: key is a valid number in the range (min <= key <= max)
*/
public int doBinarySearch(int key)
{
int low = min;
int high = max;
int c = 1;
while(low <= high){
int mid = (low+high)/2;
if(mid == key){
return c;
}
else if(mid < key){
low = mid +1;
c ++;
}
else{
high = mid -1;
c++;
}
}
return c;
}
public static void main(String[] args)
{
//start testing with 10 number, then increase to
// a hundred, a thousand, etc.
int[] answers = {3,4,10};
BinarySearch b = new BinarySearch(0,10);
int result = b.doBinarySearch(6);
int index = 0;
if (answers[index] != result)
{
System.out.println("0,10 search error.");
System.out.println("Expected: " + answers[index]);
System.out.println("Result: " + result);
}
index++;
BinarySearch c = new BinarySearch(0,100);
result = c.doBinarySearch(5);
if (answers[index] != result)
{
System.out.println("0,100 search error.");
System.out.println("Expected: " + answers[index]);
System.out.println("Result: " + result);
}
index++;
BinarySearch d = new BinarySearch(0,1000);
result = d.doBinarySearch(670);
if (answers[index] != result)
{
System.out.println("0,1000 search error.");
System.out.println("Expected: " + answers[index]);
System.out.println("Result: " + result);
}
System.out.println("Tests Completed");
}
}