Created
December 28, 2024 03:23
-
-
Save marttp/a83f0cbc93e812ef7ff2b3a96dce1720 to your computer and use it in GitHub Desktop.
Binary Search - Iterative - Java
This file contains hidden or 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
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