Collection Programs

LinkedList Binary Search

In this chapter, we will

  • Create linkedlist
  • Add elements to linkedlist
  • Sort the current linkedlist
  • Travese the sorted list using iterator
  • Perform binary search operation on linkedlist for any key.

Binary Search operation can be performed only on sorted list. 

Example: Binary search using linked list in java

package javaRadarLinkedList;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

public class SortLinkedList {

     public static void main(String[] args) {

       //create Linked List
         LinkedList javaRadarList = new LinkedList();

       //Add elements to LinkedList

         //use iterator to traverse list
          System.out.println("Before sorting: " +javaRadarList);

          Collections.sort(javaRadarList); //sorting list element

          Iterator itrAfterSort = javaRadarList.iterator();
          System.out.println("After Sorting:");


               String token = itrAfterSort.next();


              //Binary Search can be performed on Sorted List

                int i=Collections.binarySearch(javaRadarList, "Spring");
                System.out.println("Given Key is present at index :"+ i +" on sorted list");




Before sorting: [Java, Jquery, Spring, Hibernate, EJB]
After Sorting:
Given Key is present at index :4 on sorted list

We have not used the Generics in above example.

To do so just replace,

LinkedList javaRadarList = new LinkedList(); with LinkedList<E> javaRadarList = new LinkedList<E>();

E→just place the type of object (eg, String, Integer, User-defined object, etc.) that you want the LinkedList to have.

For detail example on Generics, you can also see the LinkedList add items example


Please Share this page
Views : 28