-
Notifications
You must be signed in to change notification settings - Fork 92
/
BinarySearch.java
44 lines (37 loc) · 1.09 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
import java.util.Scanner;
class BinarySearchExample
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
array = new int[num];
System.out.println("Enter " + num + " integers");
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();
System.out.println("Enter the search value:");
item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}
}