-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
55 lines (51 loc) · 1.51 KB
/
Copy pathBinarySearch.java
File metadata and controls
55 lines (51 loc) · 1.51 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
// Binary Search
package codingbat;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class BinarySearch {
static int set[] = new int[10];
public static void generateRandom(){
Random r = new Random();
for(int i = 0; i < 10; i++){
int ran = r.nextInt(100);
set[i] = ran;
}
// Sorting the set.
Arrays.sort(set);
for(int i = 0; i < set.length; i++){
System.out.println("Debug 1: sorted array = "+set[i]);
}
}
public static void binSearch(int num){
int a = 0;
int b = set.length-1;
int c = 0;
while(true){
c = (a+b)/2;
if(num == set[c]){
System.out.println("Yes! The number exists in the set.");
break;
}
else{
if(b-a == 1){
System.out.println("No! The number does not exist.");
break;
}
else if(num < set[c]){
b = c;
}
else if(num > set[c]){
a = c;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
generateRandom();
System.out.println("Enter the number you wish to search for:");
int num = sc.nextInt();
binSearch(num);
}
}