Collections.binarySearch in JAVA
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BinarySearchExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9));
int key = 5;
int index = Collections.binarySearch(list, key);
if (index >= 0) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found. Insertion point: " + (-index - 1));
}
}
}
// If you are working with arrays, you would use Arrays.binarySearch.
No comments:
Post a Comment