Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Binary_Search #117

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions Binary_Search
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java .util.Arrays;

public class BinarySearch {

public static void main(String[] args) {
int arr[]=new int[1024];
int mid=(arr.length-1)/2;
BinarySearch ob=new BinarySearch();
int i=0;
try {
FileInputStream fstream=new FileInputStream("File 1.txt");
DataInputStream in=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String s;
while((s=br.readLine())!=null)
{
arr[i]=Integer.parseInt(s);
i++;
}
Arrays.sort(arr);
Scanner sc=new Scanner(System.in);
int value=arr[mid];

long start=System.nanoTime();

int p=ob.BinarySearch(arr,value);

long end=System.nanoTime();
System.out.println((end-start));

System.out.println("number found at : "+p);
}
catch(Exception e) {
System.out.println("error:"+e.getMessage());
}

}

int BinarySearch(int[] arr, int key) {
int n=arr.length;
int low=0;
int high=n-1;
while(low<=high)
{
int mid=(low+high)/2;
if(key==arr[mid])
return mid;
else if(key<arr[mid])
high=mid-1;
else if(key>arr[mid])
low=mid+1;

}

return -1;
}
}