Collections.binarySearch(List, E): This method is available in java.util.Collections class of Java.
Syntax:
<E> int java.util.Collections.binarySearch(List<? extends Comparable<? super E>> list, E key)
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 natural ordering of its elements
Parameters: Two parameters are required for this method.
list: the list to be searched.
key: the key to be searched for.
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 CollectionsbinarySearch {public static void main(String[] args) {List<Integer> arrlist = new ArrayList<Integer>();arrlist.add(12);arrlist.add(14);arrlist.add(15);arrlist.add(20);Integer key = 15;System.out.println(Collections.binarySearch(arrlist,key));}}
Output:
2
No comments:
Post a Comment