Computer Science 132
Introduction To Computing II

Dickinson College
Fall Semester 2001
Grant Braught


import tio.*;

/**
 * RecursiveBinarySearch.java - 
 *   Performs a selection sort on a random array
 *   of integers and then applies binary search
 *   to find the location of an integer in the
 *   array.  The implementation of the binary
 *   search in this program is recursive.
 *
 * @author Grant William Braught
 * @author Dickinson College
 * @version 10/6/2000
 */
public class RecursiveBinarySearch {
    public static void main (String[] args) {

	// Create an array of 100 integers.
	int[] intArray = new int[100];
	int searchValue = 0, foundAtIndex;

	// Fill the array with random integers in a 
	// specified range.
	randomFillArray(intArray, 1, 100);
	
	// Sort the array.
	sortArray(intArray);
	
	// Print out the sorted array.
	System.out.println();
	printArray(intArray);
	System.out.println();

	// Perform searches for user entered values.  Continue
	// performing searches until the user enters -99.
	while (searchValue != -99) {
	    System.out.print("Enter a number to search for [-99 to quit]: ");
	    searchValue = Console.in.readInt();
   
	    // Search the array for the value...
	    foundAtIndex = binarySearch(intArray, 0,
					intArray.length - 1,
					searchValue);

	    // Print a message showing the search results.  If the
	    // returned index is -1 the value was not found.
	    if (foundAtIndex != -1) {
		System.out.println(searchValue + " was found at index " + 
				   foundAtIndex + ".");
	    }
	    else {
		System.out.println(searchValue + " was not found in the " +
				   "array.");
	    }
	}
    }

    /**
     * Perform a binary search on a sorted array of integers.
     * 
     * @param searchMe a sorted array of integers to be searched.
     * @param startIndex index of the left edge of the remaining
     *                   array.
     * @param endIndex index of the right edge of the remaining
     *                 array
     * @param findMe an integer to be found in the sorted array.
     *
     * @return the index in the array at which findMe was found.
     *         Or -1 if findMe is not contained in the array.
     */
    static int binarySearch(int[] searchMe, int startIndex,
			    int endIndex, int findMe) {

	// Find the midpoint of the remaining array.
	// Note that this rounds down because of the 
	// integer division.
	int midPoint = (startIndex + endIndex) / 2;


	// Does the midPoint contain findMe?
	if (searchMe[midPoint] == findMe) {
	    return midPoint;
	}
	// Are we down to the last element?  If so then
	// findMe is not in the array.
	else if (startIndex >= endIndex) {
	    return -1;
	}
	// If the midPoint contains a value > findMe
	// then search again in the left half
	// of the array (startIndex...midPoint-1).
	else if (searchMe[midPoint] > findMe) { 
	    return binarySearch(searchMe, startIndex,
				midPoint - 1, findMe);
	}
	// The midPoint must contain a value < findMe
	// so search again in the right half of the
	// array (midPoint + 1...endIndex)
	else {
	    return binarySearch(searchMe, midPoint + 1,
				endIndex, findMe);
	}   
    }

    /**
     * Sort an array of integers using the Selection Sort
     * algorithm.
     *
     * @param sortMe the array to be sorted.
     */
    static void sortArray(int[] sortMe) {
	int j;

	// For each index of the array find the item that
	// belongs in that index and put it there.
	for (int i=0; i<sortMe.length-1; i++) {
	    
	    // Find the index of the minimum element in 
	    // the array in indexes >= i
	    j = findMinIndex(sortMe,i);
	    
	    // Swap the ith element with the jth element.
	    // This puts the correct value into the ith 
	    // index.  So the array is now sorted up to
	    // and including the ith element.
	    swapArrayElements(sortMe,i,j);
	}
    }

    /**
     * Scan an array of integers starting at a specified 
     * location and return the index of the smallest integer
     * found.
     *
     * @param scanMe the array to be scanned.
     * @param start the index at which to start the scan.
     *
     * @return the index of the minimum element found in the
     *         scan.
     */
    static int findMinIndex(int[] scanMe, int start) {

	// Assume for now that the first element is 
	// the smallest.
	int minIndex = start;
	
	// Scan each element of the array.
	for (int i=start + 1; i<scanMe.length; i++) {

	    // If the ith element is smaller than all
	    // of the previous elements then i is the 
	    // index of new smallest element. 
	    if (scanMe[i] < scanMe[minIndex]) {
		minIndex = i;
	    }
	}

	return minIndex;
    }

    /**
     * Swap two elements in an array of integers.
     *
     * @param intArray the array containing the elements to
     *                 be swapped.
     * @param i the index of one of the elements to swap.
     * @param j the index of the other element to swap. 
     */
    static void swapArrayElements(int[] intArray, int i, int j) {
	int tmp;

	tmp = intArray[i];
	intArray[i] = intArray[j];
	intArray[j] = tmp;
    }

    /**
     * Fill the array passed as the parameter with
     * random integers between min and max.
     * 
     * @param fillMe the array to be filled with random integers.
     * @param min the minimum random integer to use.
     * @param max the maximum random integer to use.
     */
    static void randomFillArray(int[] fillMe, int min, int max) {

	for (int i=0; i < fillMe.length; i++) {
	    fillMe[i] = randomInt(min,max);
	}
    }

    /**
     * Generate a random integer in the range [min...max]
     *      
     * @param min the minimum random integer to use.
     * @param max the maximum random integer to use.
     *
     * @return a random integer in the range [min...max].
     */
    static int randomInt(int min, int max) {

	// max - min + 1 gives the number of possible values
	// the random integer can have.  A number from 0 to
	// max - min + 1 is generated.  That value is shifted
	// upward by min and cast as an integer to drop the
	// decimal.
	return (int)((max-min+1)*Math.random()+min);
    }

    /**
     * Print the contents of an integer array to the screen.
     *
     * @param printMe the array to be printed.
     */
    static void printArray(int[] printMe) {
	
	// Print out all but the last element separated
	// by commas.
	for (int i=0; i<printMe.length-1; i++) {
	    System.out.print(printMe[i] + ", ");
	}

	// Print out the last element and a new line.
	System.out.println(printMe[printMe.length-1]);
    }
}




RecursiveBinarySearch.java : javadoc documentation.