Skip to content

Instantly share code, notes, and snippets.

@thomashw
Created February 21, 2012 16:18
Show Gist options
  • Save thomashw/1877223 to your computer and use it in GitHub Desktop.
Save thomashw/1877223 to your computer and use it in GitHub Desktop.
Example of implementing binary search.
import java.io.*;
public class BinarySearch
{
public int[] a;
public BinarySearch()
{
a = new int[] { 0, 1, 2, 3, 4, 8, 10, 14 };
}
private int bin_search( int val, int beg, int end )
{
int mid = (beg + end) / 2;
if( a[mid] == val )
return mid;
if( beg >= end )
return -1;
if( val < a[mid] )
end = mid - 1;
else
beg = mid + 1;
return bin_search( val, beg, end );
}
public static void main( String[] args ) throws IOException
{
BinarySearch bs = new BinarySearch();
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
String input = " ";
while( input.charAt(0) != 'q' ) {
System.out.println( "Enter a number to search for: " );
input = br.readLine();
if( input.charAt(0) == 'q' )
break;
int val = Integer.parseInt( input );
System.out.println( "Index of value in array: " + bs.bin_search( val, 0, bs.a.length - 1 ) );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment