VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bubble-sort-for-linked-list-by-swapping-nodes/

⇱ Bubble Sort for Linked List by Swapping nodes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bubble Sort for Linked List by Swapping nodes

Last Updated : 11 Jul, 2025

Given a singly linked list, sort it using bubble sort by swapping nodes.  

Examples:

Input: 5 -> 1 -> 32 -> 10 -> 78
Output: 1 -> 5 -> 10 -> 32 -> 78

Input: 20 -> 4 -> 3
Output: 3 -> 4 -> 20

Approach:

To apply Bubble Sortto a linked list, we need to traverse the list multiple times, comparing adjacent nodes and swapping their positions by adjusting their links if the current node's data is greater than the next. During each pass, the largest unsorted element moves to its correct position at the end of the list. This process continues until no more swaps are needed, indicating that the list is sorted.

Below is the implementation of the above approach: 


Output
1 5 10 32 78 

Time complexity: O(n^2) , where n is the number of nodes in the Linked List.
Auxiliary space: O(1)

Comment
Article Tags:
Article Tags: