Collections.binarySearch(List, E, Comparator) in Java

Collections.binarySearch(List, E, Comparator): This method is available in java.util.Collections class of Java.

Syntax:

<E> int java.util.Collections.binarySearch(List<? extends E> list, E key, Comparator<? super E> c)

This method takes three arguments. This method searches the specified list for the specified object using the binary search algorithm.

Note: The list must be sorted into ascending order according to the specified comparator.

Parameters: Three parameters are required for this method.

list: the list to be searched.

key: the key to be searched for.

c: the comparator by which the list is ordered. A null value indicates that the elements' natural ordering should be used.

Returns: the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1).

Note: The insertion point is defined as the point at which the key would be inserted into the list.

Exceptions: NA

Approach

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsbinarySearch2 {
    public static void main(String[] args) {

        List<Integer> arrlist = new ArrayList<Integer>();

        arrlist.add(18);
        arrlist.add(15);
        arrlist.add(12);
        arrlist.add(10);
        arrlist.add(7);
        arrlist.add(5);

        int key = 7;
        int index = Collections.binarySearch(arrlist,
key, Collections.reverseOrder());

        System.out.println(index);

    }
}

Output:

4


No comments:

Post a Comment