Do binary search

static<T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
Searches the specified list for the specified object using the binary search algorithm.
static<T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
Searches the specified list for the specified object using the binary search algorithm.

  import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

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));
    }
  }
}
  

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

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:


Sorted list: [length: 7]
[B, H, H, L, M, M, R]
Found M @ 5
Didn't find J @ -4
Home 
  Java Book 
    Collection  

Collections:
  1. Collections
  2. Get empty collection from Collections
  3. Do binary search
  4. Copy value to a List
  5. Get Enumeration from collection, create list from Enumeration
  6. Fill a list
  7. Get the max and min value from a Collection
  8. Fill n Copy object to a list
  9. Replace value in a list
  10. Reverse a list
  11. Get comparator in reverse order
  12. Rotate and shuffle a list
  13. Create singleton
  14. Sort a list
  15. Swap element in a list
  16. Get a synchronized collection
  17. Return an unmodifiable view of collections