List binary search

In this chapter you will learn:

  1. How to do binary search on a List
  2. How to use the not-in index value returned from binary search to insert value

Sort a list

We can do binary search on an ordered list with the following methods.

  • static<T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
    Searches list for an object using the binary search algorithm.
  • static<T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
    Searches list for an object using the binary search algorithm and passed in comparator.
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
//from  j a  va 2  s  . c o m
public class Main {

  public static void main(String args[]) {
    List<Character> ll = new LinkedList<Character>();

    for (char n = 'A'; n <= 'Z'; n++)
      ll.add(n);

    Collections.shuffle(ll);

    for (Character x : ll)
      System.out.print(x + " ");
    Collections.sort(ll);

    for (Character x : ll)
      System.out.print(x + " ");

    System.out.println("Searching for F.");
    int i = Collections.binarySearch(ll, 'F');

    if (i >= 0) {
      System.out.println("Found at index " + i);
      System.out.println("Object is " + ll.get(i));
    }
  }
}

The code above generates the following result.

Search value not in the List

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
//from   j a  v  a 2 s  .co m
public class MainClass {
  public static void main(String args[]) {
    String simpsons[] = { "B", "H", "L", "M", "H", "M", "R" };

    List list = new ArrayList(Arrays.asList(simpsons));

    // Ensure list sorted
    Collections.sort(list);
    System.out.println("Sorted list: [length: " + list.size() + "]");
    System.out.println(list);

    // Search for element in list
    int index = Collections.binarySearch(list, "M");
    System.out.println("Found M @ " + index);

    // Search for element not in list
    index = Collections.binarySearch(list, "J");
    System.out.println("Didn't find J @ " + index);

  }
}

The output:

The -4 is returned from the binary search when searching J since J is not in the list. -4 is negative and negative indicates that the value is missing. The absolute value of -4 tells where should we insert and can still keep the list ordered.

Next chapter...

What you will learn in the next chapter:

  1. Return an unmodifiable view of collections
  2. What if you try to change an unmodifiable collection
Home » Java Tutorial » Collections

List interface
List add/insert elements
List clear/remove elements
List search
List element get and set
List and its Iterator
List size, empty
List conversion, to array
List to sublist
List comparison
ArrayList
ArrayList Creation
ArrayList add/insert
ArrayList get/set element
ArrayList clear/remove
ArrayList search
ArrayList copy and shallow copy
ArrayList size, trim to size and capacity
ArrayList to array
LinkedList class
LinkedList creation
LinkedList add/insert elements
LinkedList get elements
LinkedList search
LinkeList replace/set elements
LinkedList remove element
LinkedList copy
LinkedList iterator
LinkedList peek element
LinkedList pop/push element
LinkedList conversion
Map interface
Map element adding
Map.Entry class
Map key
Map value
Map key/value search
Map delete/remove
Map comparison
HashMap Class
HashMap search
HashMap clone
TreeMap
TreeMap key
TreeMap head sub map
TreeMap tail sub map
TreeMap sub map
NavigableMap
NavigableMap key
NavigableMap key-value pair
LinkedHashMap Class
IdentityHashMap
SortedMap
HashSet
HashSet element adding
HashSet element removing and clearing
HashSet clone
HashSet iterator
HashSet properties
TreeSet
TreeSet elements adding
TreeSet subSet
NavigableSet
LinkedHashSet
Iterator
ListIterator
List filling
List reversing
List rotating and shuffling
List sorting
List element swap
List element replacing
List copy
List binary search
Collection unmodifiable
Collection synchronized
Collection singleton
Collection max/min value
Empty Collections
Comparator
Comparable
Enumeration
EnumSet
EnumMap Class
PriorityQueue