Skip to content

Instantly share code, notes, and snippets.

@marttp
Created December 28, 2024 03:23
Show Gist options
  • Save marttp/a83f0cbc93e812ef7ff2b3a96dce1720 to your computer and use it in GitHub Desktop.
Save marttp/a83f0cbc93e812ef7ff2b3a96dce1720 to your computer and use it in GitHub Desktop.
Binary Search - Iterative - Java
import java.util.List;
public class Playground {
public static void main(String[] args) {
var nums = List.of(1, 2, 3, 15, 35, 53, 81);
System.out.println("Element 35 exists: " + binarySearch(nums, 35));
System.out.println("Element 40 exists: " + binarySearch(nums, 40));
}
private static boolean binarySearch(List<Integer> nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int curr = nums.get(mid);
if (curr == target) {
return true;
} else if (curr < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment