Skip to content

Commit

Permalink
Merge pull request #2 from Abhigupta4981/patch-1
Browse files Browse the repository at this point in the history
created java program for binary search
  • Loading branch information
i-vishi authored Oct 1, 2018
2 parents 1a69c8a + 2c60c4a commit a06e7ea
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions binarySearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import java.util.*;
import java.io.*;
class BinarySearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
System.out.println("Enter the array in sorted order");
for(int i = 0; i<n; i++)
a[i] = sc.nextInt();
int low = 0;
int high = n-1;
int key = sc.nextInt();
int ans = -1;
while(low<=high) {
int mid = (low+high)>>1;
if(a[mid]==key) {
ans = mid;
break;
}
if(a[mid]<key)
low = mid+1;
else
high = mid-1;
}
System.out.println(ans);
}
}

0 comments on commit a06e7ea

Please sign in to comment.