Skip to content

Instantly share code, notes, and snippets.

@cgoodmac
Created August 1, 2013 00:15
Show Gist options
  • Save cgoodmac/6127435 to your computer and use it in GitHub Desktop.
Save cgoodmac/6127435 to your computer and use it in GitHub Desktop.
Recursive binary search
public class Search {
private Search() {
super();
}
/**
* @param array A sorted array of ints to search through. This must be sorted.
* @param searchTerm An int to search the array for
* @return Whether the searchTerm exists in the array
*/
public static boolean binarySearch(int[] array, int searchTerm) {
/*
TODO: Fill this in. Note that you can either make copies of the array
as you search, or perform the search without ever copying the array.
Start with the former, then try for the latter.
*/
// throw new NotImplementedException();
// return false;
// compare the search term to the middle index;
if ( array.length == 0 ) {
return false;
} else if ( array.length == 1 && array[0] != searchTerm) {
return false;
}
int midIndex = array.length / 2;
if (searchTerm == array[midIndex] ) {
return true;
} else if (searchTerm < array[midIndex]) {
int[] newArray = new int[midIndex];
for (int i = 0; i < midIndex; i++ ) {
newArray[i] = array[i];
}
return binarySearch(newArray, searchTerm);
} else {
int[] newArray = new int[array.length - midIndex - 1];
for (int i = 0; i < midIndex; i++ ) {
newArray[i] = array[i + midIndex];
}
return binarySearch(newArray, searchTerm);
}
}
}
@cmcenearney
Copy link

Hi Chris,

Here is a version using the less painful Arrays.copyOfRange function. Syntax note: seems you can either import and then simply call Arrays.copyOfRange or not import and preface each call with "java.utils."

import java.util.Arrays;

public class Search {
    private Search() {
        super();
    }

    /**
     * @param array A sorted array of ints to search through. This must be sorted.
     * @param searchTerm An int to search the array for
     * @return Whether the searchTerm exists in the array
     */
    public static boolean binarySearch(int[] array, int searchTerm) {

         if (array.length == 0){
            return false;
         }

         if (array.length == 1) {
             if (array[0] == searchTerm) {
                 return true;
             }
             else {
                 return false;
             }
         }

        int[] first_half = Arrays.copyOfRange(array, 0, array.length/2);
        int[] second_half = Arrays.copyOfRange(array, array.length/2, array.length);

        return binarySearch(first_half, searchTerm) || binarySearch(second_half, searchTerm);

    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment