Skip to content

Instantly share code, notes, and snippets.

@shahzadaazam
Created November 9, 2020 06:37
Show Gist options
  • Save shahzadaazam/6e04ad133983ac70e6202de655cf80d7 to your computer and use it in GitHub Desktop.
Save shahzadaazam/6e04ad133983ac70e6202de655cf80d7 to your computer and use it in GitHub Desktop.
Binary search iterative solution
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