Created
May 23, 2013 16:34
-
-
Save naveenwashere/5637413 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.