Skip to content

Commit f83f2dc

Browse files
Added the recursive implementation of the binary search algorithm
1 parent 8f323f0 commit f83f2dc

3 files changed

Lines changed: 23 additions & 2 deletions

File tree

‎src/com/sketch/Main.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
public class Main {
66
public static void main(String[] args){
77
int[] sortedArray = { 1, 2, 3, 5, 7, 9, 11, 14, 17, 26, 18, 37, 42, 43, 44, 47, 48, 49, 78, 227, 5556, 8976 };
8-
int valueToFind = 5556;
8+
int valueToFind = 18;
99

10-
int binarySearchIndex = BinarySearch.searchDefault(sortedArray, valueToFind);
10+
int binarySearchIndex = BinarySearch.searchRecursive(sortedArray, valueToFind, 0, sortedArray.length - 1);
1111

1212
System.out.println("Expected Value Index: 20");
1313
System.out.println("Actual Value Index: " + binarySearchIndex);

‎src/com/sketch/search/binarysearch/BinarySearch.java‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,23 @@ else if(middleNumber < numberToFind){
2727
public static int searchDefault(int[] sortedNumbers, int numberToFind){
2828
return Arrays.binarySearch(sortedNumbers, numberToFind);
2929
}
30+
31+
public static int searchRecursive(int[] sortedNumbers, int numberToFind, int low, int high){
32+
if(low > high){
33+
return -1;
34+
}
35+
int middlePosition = (low + high) / 2;
36+
int middleNumber = sortedNumbers[middlePosition];
37+
if(middleNumber == numberToFind){
38+
return middlePosition;
39+
}
40+
else if(middleNumber < numberToFind){
41+
low = middlePosition + 1;
42+
return searchRecursive(sortedNumbers, numberToFind, low, high);
43+
}
44+
else {
45+
high = middlePosition - 1;
46+
return searchRecursive(sortedNumbers, numberToFind, low, high);
47+
}
48+
}
3049
}

‎src/com/sketch/search/binarysearch/BinarySearch.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ find a target value or optimal answer in logarithmic time **O(log N**.
55

66
![img.png](img.png)
77

8+
Implementation: [BinarySearch.java](./BinarySearch.java)
9+
810
The Binary Search algorithm can only be applied to data-structures that:
911
- are sorted,
1012
- and access to any element of the data-structure takes constant time **O(1)**.

0 commit comments

Comments
 (0)