Tutorials

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
         javaRadarList.add("Java");
         javaRadarList.add("Jquery");
         javaRadarList.add("Spring");
         javaRadarList.add("Hibernate");
         javaRadarList.add("EJB");

         //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:");

             while(itrAfterSort.hasNext()){

               String token = itrAfterSort.next();
               System.out.println(token);

              }

              //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");

            }

}

OUTPUT

Before sorting: [Java, Jquery, Spring, Hibernate, EJB]
After Sorting:
EJB
Hibernate
Java
Jquery
Spring
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