Created
November 9, 2020 06:37
-
-
Save shahzadaazam/6e04ad133983ac70e6202de655cf80d7 to your computer and use it in GitHub Desktop.
Binary search iterative solution
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,4)); | |
} | |
public static boolean binarySearch(int[] arr, int num) { | |
int low = 0; | |
int high = arr.length-1; | |
while (low <= high) { | |
// base case | |
int mid = (low + high)/2; | |
if (arr[mid] == num) { | |
return true; | |
} | |
if (num < arr[mid]) { | |
low = 0; | |
high = mid-1; | |
} else { | |
low = mid + 1; | |
high = arr.length-1; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment