Java List binary search

Description

Java List binary search


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

public class Main {
  public static void main(String[] args) {
    List<String> list = new LinkedList<String>();

    list.add("CSS");
    list.add("HTML");
    list.add("C++");
    list.add("Java");
    list.add("SQL");
    list.add("Javascript");
    //w ww  .j  a v a  2s.  c  om
    Collections.sort(list);
    System.out.println(list);
    int index = Collections.binarySearch(list, "C++");
    
    if (index > 0) {
      System.out.println("Found at index = " + index);
      String month = (String) list.get(index);
      System.out.println(month);
    }
    
    index = Collections.binarySearch(list, "NewLang");
    
    if (index < 0) {
      System.out.println("you can insert at index = " + -index);
    }
  }
}



PreviousNext

Related