Created
November 9, 2020 05:17
-
-
Save shahzadaazam/12c534b3f4f26f4c172b6aec2a97bb0f to your computer and use it in GitHub Desktop.
Binary search recursive implementation
This file contains 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
class BinarySearch { | |
public static void main(String[] args) { | |
int[] arr = new int[]{1, 2, 3, 4, 5}; | |
System.out.println(binarySearch(arr, 0, arr.length-1, 5)); | |
} | |
public static boolean binarySearch(int[] arr, int left, int right, int num) { | |
if (left <= right) { | |
int mid = (left + right) / 2; | |
// base case | |
if (arr[mid] == num) { | |
return true; | |
} | |
if (num < arr[mid]) { | |
return binarySearch(arr, left, mid-1, num); | |
} else { | |
return binarySearch(arr, mid+1, right, num); | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment