-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
65 lines (62 loc) · 1.63 KB
/
BinarySearch.java
File metadata and controls
65 lines (62 loc) · 1.63 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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package coding;
/**
*
* @author Sunil Shetty
*/
import java.util.*;
public class BinarySearch {
int binarysearch(int arr[],int low,int high,int key)
{
if(high>=low)
{
int mid = (low+high)/2;
if(arr[mid]==key)
{
return mid;
}
if(arr[mid]>key)
{
return binarysearch(arr,low,mid-1,key);
}
else
{
return binarysearch(arr,mid+1,high,key);
}
}
return -1;
}
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
BinarySearch bs= new BinarySearch();
System.out.println("enter the number of elements: ");
int n=in.nextInt();
int arr[] = new int[n];
System.out.println("enter the elements");
for(int i=0;i<n;i++)
{
arr[i]=in.nextInt();
}
System.out.println("Array before swaping: ");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
int length=arr.length;
System.out.println("array length is: "+length);
System.out.println("Enter the value of key: ");
int x=in.nextInt();
int result = bs.binarysearch(arr,0,length-1,x);
if(result==-1)
{
System.out.println("Element not present");
}
else
System.out.println("Element found at index "+result);
}
}