Fig02_09 - /* 7*/ high = mid - 1; else /* 8*/ return mid;...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
import DataStructures.Comparable; import DataStructures.MyInteger; i public class Fig02_09 { public static final int NOT_FOUND = -1; /* START: Fig02_09.txt*/ /** * Performs the standard binary search. * @return index where item is found, or -1 if not found */ public static int binarySearch( Comparable [ ] a, Comparable x ) { /* 1*/ int low = 0, high = a.length - 1; / /* 2*/ while( low <= high ) { /* 3*/ int mid = ( low + high ) / 2; / /* 4*/ if( a[ mid ].compareTo( x ) < 0 ) /* 5*/ low = mid + 1; /* 6*/ else if( a[ mid ].compareTo( x ) > 0 )
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: /* 7*/ high = mid - 1; else /* 8*/ return mid; // Found } /* 9*/ return NOT_FOUND; // NOT_FOUND is defined as -1 } /* END */ / // Test program public static void main( String [ ] args ) { int SIZE = 8; Comparable [ ] a = new MyInteger [ SIZE ]; for( int i = 0; i &amp;lt; SIZE; i++ ) a[ i ] = new MyInteger( i * 2 ); for( int i = 0; i &amp;lt; SIZE * 2; i++ ) System.out.println( &amp;quot;Found &amp;quot; + i + &amp;quot; at &amp;quot; + binarySearch( a, new MyInteger( i ) ) ); } }...
View Full Document

Ask a homework question - tutors are online