Skip to content

Commit

Permalink
added recursiveBinSearch, untested
Browse files Browse the repository at this point in the history
also changed spacing and order of statements in main for consistency
  • Loading branch information
loucadufault authored May 4, 2019
1 parent 240c133 commit ecd95ff
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion Algorithms/binarySearch/src/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@ private static boolean iterativeBinarySearch(int[] data, int key) {

return data[left] == key;
}

private static boolean recursiveBinarySearch(int[] data, int key) {
if (data.length == 1) {
return data[0] == key;
} else {
int left = 0;
int right = data.length;
int mid = (left + right)/2;

if (key > data[mid-1]) {
return recursiveBinarySearch(Arrays.copyOfRange(data, mid, data.length), key);
} else {
return recursiveBinarySearch(Array.copyOfRange(data, 0, mid), key);
}
}
}

private static int[] initRandom(int size, int range) {
//returns an array of random integers with no duplicates
Expand Down Expand Up @@ -47,7 +63,12 @@ public static void main(String[] args) {
Random random = new Random();
int testKey = random.nextInt(RANGE);

boolean found = iterativeBinarySearch(testArr, testKey);
boolean iterativeFound = iterativeBinarySearch(testArr, testKey);
boolean recursiveFound = recursiveBinarySearch(testArr, testKey);

assert (iterativeFound == recursiveFound);
boolean found = iterativeFound;

System.out.println("Searching the test array: " + Arrays.toString(testArr));
System.out.println("For the test key: " + testKey);
if (found) {
Expand Down

0 comments on commit ecd95ff

Please sign in to comment.