-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinarySearch.java
66 lines (58 loc) · 1.63 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.Scanner;
public class binarySearch
{
public static void main(String args[])
{
//declaration
Scanner sc = new Scanner(System.in);
int n, position, key;
int[] a;
int low, high, mid;
boolean flag;
//reading the number of array elements
System.out.println("Enter the number of array elements: ");
n = sc.nextInt();
//creating an array of size n
a = new int[n];
//reading the array elements
System.out.println("Enter " + n + " array elements");
for(int i = 0 ; i < n ; i++)
{
a[i] = sc.nextInt();
}
//reading the array element to be found/searched
System.out.println("Enter th number to be found: ");
key = sc.nextInt();
//initialization
low = 0; high = n-1; mid = 0; position = 0;
flag = false;
//Binary search
while(low <= high)
{
mid = (low + high) / 2;
if( key == a[mid])
{
flag = true;
position = mid+1;
break;
}
else if( key < a[mid] )
{
high = mid -1 ;
}
else if( key > a[mid] )
{
low = mid + 1;
}
}
//display syatement
if( flag == true )
{
System.out.println(key + " is found at position " + position );
}
else
{
System.out.println(key + " is NOT found");
}
}
}