Thursday 7 March 2024

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

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...