forked from ranjansharma255/Java_Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
73 lines (72 loc) · 1.46 KB
/
BinarySearch.java
File metadata and controls
73 lines (72 loc) · 1.46 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
import java.lang.*;
import java.util.Scanner;
class BinarySearch
{
int binaryRecursive (int a[] , int low, int high, int key)
{
int mid;
if(low == high)
{
if(key == a[high])
{
return low;
}
else
return 0;
}
else{
mid = low + (high - low)/2;
if(key == a[mid])
{
return mid;
}
else if (key < a[mid])
{
return binaryRecursive(a,low,mid-1,key);
}
else
{
return binaryRecursive(a,mid+1,high,key);
}
}
}
public static void main(String[] args)
{
System.out.println("Binary Search Recursive");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the array elements");
for(int i=0; i<arr.length; i++)
{
arr[i] = sc.nextInt();
}
System.out.println("Enter the element to be searched ");
int key = sc.nextInt();
// sorting the array in ascending order
for(int i=0; i<arr.length; i++)
{
for(int j=i+1; j<arr.length; j++)
{
if(arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
BinarySearch rb = new BinarySearch();
int k = rb.binaryRecursive(arr, 0, size, key);
if(k==0)
{
System.out.println("Element is not found");
System.out.println(k);
}
else
{
System.out.println("Element is found at the index " + (k+1));
}
}
}