CSC108 Lecture #12 - Binary Search


The example in lecture searches through an array of elements in a phone book (each element would have a name and a phone number). This example searches through an array of integers.


BinarySearch.java

// Binary Search Algorithm: Searches for x in an array of integers.
//   Keep dividing the list into two, until begin and end are within one.

class BinarySearch {
  public static void main (String[] args) {
	int[] book = {2, 4, 5, 7, 8, 9, 12, 15};

	int   x = 12;  // The number we're looking for
	System.out.println ("Search Key is " + x);

	int mid;
	int begin = 0;
	int end = book.length-1;

	while (begin != end-1) {
		mid = (begin+end)/2;
		if (book[mid] > x)
			end = mid;
		else
			begin = mid;
	}

	if (book[begin] == x)
		System.out.println ("Found value   " + book[begin]);
	// Special case where element is found at last index.
	else if (begin+1 < book.length && book[begin+1] == x)
		System.out.println ("Found value   " + book[begin+1]);
	else
		System.out.println ("Value not found.");
  }
}

[ CSC108 Home | Outline | Announcements | Newsgroup | Assignments | Lectures | Marks | Links ]


U of T IMAGE

© Copyright 2000. All Rights Reserved.