Created
August 1, 2013 00:15
-
-
Save cgoodmac/6127435 to your computer and use it in GitHub Desktop.
Recursive binary search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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."