-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.java
50 lines (38 loc) · 1.05 KB
/
BinarySearch.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
package com.SearchAlgorithms;
public class BinarySearch {
public static void main(String[] args) {
/**
* Creating Sorted Array
*/
int []numbers = new int[(int) Math.pow(2,10)];
for(int i=0; i<(int)Math.pow(2,10) ; i++){
numbers[i] = i;
}
// Pick a number to make computer guess it
int myNumber = 1;
// Bounds, counters, and average variables
int left = 0;
int right = (int)Math.pow(2,11);
int temp = ((left+right)/2);
int count = 0;
// Main loop of the Binary Search
while( left<right ){
System.out.println("Start Left - "+left+" right - "+right+" Average - "+ temp);
temp = ((left+right)/2);
if( temp == myNumber ){
count++;
System.out.println(" Found my number is "+myNumber+" -- #"+ count+"times");
break;
}
else if( temp < myNumber ){
left = temp;
}
else{
right = temp;
}
count++;
System.out.println(count + "-th try ");
System.out.println(" Left - "+left+" right - "+right+" Average - "+ temp);
}
}
}