Java Collections.binarySearch Example

Java Collections.binarySearch is a useful method for finding and element in a list or inserting an entry in the correct ordered position within a collection.

   CollectionsTest.java


package preiss.collectionsbinarysearch;
// Java program to demonstrate working of Collections.binarySearch
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class CollectionsTest {
	
	    public static void main(String[] args)
	    {
	        List al = new ArrayList();
	        
	        al.add(2);
	        al.add(3);
	        al.add(10);
	        al.add(20);
	        
	        //to get insertion point for elements not present: add 1 to answer and then multiply by -1
	 
	        System.out.println("list size: " + al.size());
	        System.out.println();
	        
	        int index = Collections.binarySearch(al, 2);
	        System.out.println("2 is at position: " + index);
	        
	        index = Collections.binarySearch(al, 3);
	        System.out.println("3 is at position: " + index);
	        
	        // 10 is present at index 2.
	         index = Collections.binarySearch(al, 10);
	        System.out.println("10 is at position: " + index);
	        
	         index = Collections.binarySearch(al, 20);
	        System.out.println("20 is at position: " + index);
	        
	        System.out.println();
	        
	        index = Collections.binarySearch(al, 0);
	        System.out.println("0 would be at position: " + index);
	        
	        index = Collections.binarySearch(al, 1);
	        System.out.println("1 would be at position: " + index);
	 
	        // 15 is not present. 15 would have been inserted
	        // at position 3. So the function returns (-4-1) 
	        // which is -4. ie (-insertion point - 1)
	        index = Collections.binarySearch(al, 15);
	        System.out.println("15 would be at position: " + index);
	        
	        index = Collections.binarySearch(al, 25);
	        System.out.println("25 would be at position: " + index);
	        
	        index = Collections.binarySearch(al, 35);
	        System.out.println("35 would be at position: " + index);
	    }
	

}

Pin It on Pinterest

Share This