VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-sort-linkedlist-using-comparable/

⇱ Java Program to Sort LinkedList using Comparable - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Sort LinkedList using Comparable

Last Updated : 23 Jul, 2025

In Java, LinkedList is a part of the collection framework provided in java.util package. LinkedList is a linear data structure where all the elements are unsorted in contiguous memory locations. The advantage of LinkedList is it is dynamic and easy to insert and delete any element. We can not access any node of LinkedList directly we need to start with the Head node and traverse through a LinkedList.

Comparable provides a single sorting sequence. If we use Comparable then it will affect the original class. Comparable Interface provides compareTo() method to sort elements. In java, comparable is provided by the java.lang package. We can sort the LinkedList by invoking the Collections.sort(List) method. 

LinkedList can be sorted in the following order using Comparable:

  1. Ascending Order
  2. Descending Order
    • Using Collections.reverseOrder()
    • Override the CompareTo() method

Type 1: Ascending Order

To sort a LinkedList in Ascending order using Comparable we need to implement the Comparable interface to our class and override the CompareTo() method to sort a LinkedList with respect to specific items. After that, we need to use Collection.sort() method to sort a LinkedList.

Syntax: Collections.sort(Listobject)

Example:


Output
UnSorted List
2 Meet 32
5 Jhon 11
1 Sham 92
3 William 86
4 Harry 35

Sorted List
1 Sham 92
2 Meet 32
3 William 86
4 Harry 35
5 Jhon 11

Time Complexity: O(n log n)

Type 2: Descending Order

To sort a LinkedList in Descending order we have two Approaches.

A. Using Collections.reverseOrder()

In this approach, we have to first sort a LinkedList in Ascending order and after that using Collections.reverseOrder() we can reverse the order of sorted LinkedList.

Syntax: Collections.sort(Listobject,Collections.reverseOrder())

Example:


Output
UnSorted List
2 Meet 32
5 Jhon 11
1 Sham 92
3 William 86
4 Harry 35

Sorted List
5 Jhon 11
4 Harry 35
3 William 86
2 Meet 32
1 Sham 92

Time Complexity: O(n log n)

B. Override the CompareTo() method

In this approach, we have to override the compareTo() method in such a way that it will return a LinkedList in descending order.

Example:


Output
UnSorted List
2 Meet 32
5 Jhon 11
1 Sham 92
3 William 86
4 Harry 35

Sorted List
5 Jhon 11
4 Harry 35
3 William 86
2 Meet 32
1 Sham 92

Time Complexity: O(n log n)

Comment