Skip to content

Instantly share code, notes, and snippets.

@naveenwashere
Created May 23, 2013 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveenwashere/5637413 to your computer and use it in GitHub Desktop.
Save naveenwashere/5637413 to your computer and use it in GitHub Desktop.
package com.algorithms;
import java.util.Arrays;
import java.util.Scanner;
public class BinarySearch {
public boolean search(int low, int hi, int[] a, int searchFor)
{
int mid = (hi + low)/2;
if(a[mid] == searchFor) return true;
else if(mid < (a.length-1) && searchFor > a[mid])
return search(mid + 1, a.length, a, searchFor);
else if(mid > 0 && searchFor < a[mid])
return search(low, mid - 1, a, searchFor);
else
return false;
}
public BinarySearch()
{
//none
}
public static void main(String[] args) throws Exception{
int[] a = {9, 6, 5, 42, 33, 44, 3, 99, 2, 87, 5, 63, 77, 51, 59};
Arrays.sort(a);
for(int i=0; i < a.length; i++)
{
System.out.print(a[i] + " ");
}
BinarySearch bs = new BinarySearch();
System.out.println("Enter element to search for: ");
Scanner in = new Scanner(System.in);
int searchingFor = in.nextInt();
System.out.print("Element " + searchingFor);
System.out.println(bs.search(0, a.length - 1, a, searchingFor) == true?" exists":" does not exist.");
}
}
@naveenwashere
Copy link
Author

This is an implementation of the Binary Search Algorithm. Please give comments and let me know if there is scope for optimization and make it efficient. As always, this is just some code I wrote for my revision of Algorithms concepts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment