DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List

In this article, we will sort a Link List using the bubble sort technique.

Example:

Input : 20->30->40->10

Output :10->20->30->40

Input : 20->4->3

Output : 3->4->20

Sorting Technique

The bubble sort technique works similarly as it takes two adjacent elements, compares them and the swaps the smaller one with larger one. At the end of pass 1, the largest element reaches its final position.

C Code:

 #include <stdio.h>
 #include <malloc.h>
 /* Link list node */
 typedef struct node {
     int data;
     struct node* next;
 } node;
 node* head = NULL;
 /*Function to create a linked list*/
 void createll()
 {
     int i, n;
     node* tail; // keeps track of the last element
     tail = head; //atm head is the last element
     int arr[4] = { 20, 30, 40, 10};
     for (i = 0; i < 4; i++) {
         node* newn;
         newn = (node*)malloc(sizeof(node)); //creates a new node in every iteration
         newn->data = arr[i];
         newn->next = NULL;
         if (head == NULL) {
             head = newn;
             tail = head;
         }
         else {
             tail->next = newn; //linking the previous last element to new last element
             tail = newn; //making the new element as the last element
         }
     }
 }
 /* Function to print linked list */
 void display()
 {
     struct node* temp = head;
     while (temp != NULL) {
         printf("%d  ", temp->data);
         temp = temp->next;
     }
     printf("\n");
 }
 /* function to swap data of two nodes a and b*/
 void swap(node* a, node* b)
 {
     int temp = a->data;
     a->data = b->data;
     b->data = temp;
 }
 /*Function to bubble sort*/
 void bubble()
 {
     int ctr, n = 1;
     node *t1, *t2;
     t1 = head;
     do {
         ctr = 0;
         t2 = head;
         while (t2->next != NULL) {
             if (t2->data > t2->next->data) {
                 swap(t2, t2->next);
                 ctr = 1;
             }
             t2 = t2->next;
         }
         t1 = t1->next;
         n++;
     } while (t1->next != NULL && ctr);
 }
 void main()
 {
     createll();
     printf("Before Sorting: ");
     display();
     bubble();
     printf("\nAfter Sorting: ");
     display();
 } 

C++ Code:

 #include <iostream>
 using namespace std;
 struct node {
     int data;
     node* next;
 }* head = NULL;
 bool Is_List_Empty()
 {
     if (head == NULL)
         return true;
     return false;
 }
 void Insert_At_End(int value)
 {
     node *temp = new node, *current = head;
     temp->data = value;
     temp->next = NULL;
     if (Is_List_Empty()) {
         head = temp;
         return;
     }
     while (current->next != NULL)
         current = current->next;
     current->next = temp;
 }
 void Bubble_Sort()
 {
     int cnt = 0;
     node* start = head;
     node* curr = NULL;
     node* trail = NULL;
     node* tmp = NULL;
     //get cnt(size) of linked list
     while (start != NULL) {
         start = start->next;
         ++cnt;
     }
     for (int i = 0; i < cnt; ++i) {
         //set curr and trail at the start node
         curr = trail = head;
         while (curr->next != NULL) {
             //compares curr and its next
             if (curr->data > curr->next->data) {
                 //swaps pointers for curr & curr->next
                 tmp = curr->next;
                 curr->next = curr->next->next;
                 tmp->next = curr;
                 //setup pointers for the head and trail if applicable
                 if (curr == head)
                     head = trail = tmp;
                 else
                     trail->next = tmp;
                 curr = tmp;
             }
             //advance pointers
             trail = curr;
             curr = curr->next;
         }
     }
 }
 void Print_Linked_List()
 {
     if (Is_List_Empty()) {
         cout << "List is Empty" << endl;
         return;
     }
     node* current = head;
     while (current->next != NULL) {
         cout << current->data << " ";
         current = current->next;
     }
     cout << current->data << endl;
 }
 int main()
 {
     int i;
     cout << "Before sorting: ";
     int arr[4] = { 20, 30, 40, 10 };
     for (i = 0; i < 4; i++)
         Insert_At_End(arr[i]);
     Print_Linked_List();
     Bubble_Sort();
     cout << "After sorting: ";
     Print_Linked_List();
     return 0;
 } 

Java Code:

 public
 class Linked_List_Bubble_Sort {
 public
     static void main(String[] args)
     {
         LinkedList list = new LinkedList();
         // Adding integers unordered
         list.insertAtTop(10);
         list.insertAtTop(40);
         list.insertAtTop(30);
         list.insertAtTop(20);
         // Prints the integers before sorting
         System.out.print("Before sorting: ");
         list.print();
         // Call BubbleSort method
         list.bubbleSort();
         // Prints out the integers after sorting
         System.out.print("After sorting: ");
         list.print();
     }
     static class Node {
     private
         int item;
     private
         Node next;
         // Constructor
     public
         Node(int newItem, Node newNode)
         {
             item = newItem;
             next = newNode;
         }
         // Getter's and Setters
     public
         int getItem()
         {
             return item;
         }
     public
         void setItem(int newItem)
         {
             item = newItem;
         }
     public
         Node getNext()
         {
             return next;
         }
     public
         void setNext(Node newNext)
         {
             next = newNext;
         }
     }
     static class LinkedList {
     private
         Node top;
     public
         LinkedList()
         {
             top = null;
         }
     public
         void insertAtTop(int value)
         {
             Node newNode = new Node(value, top);
             top = newNode;
         }
     public
         void print()
         {
             Node curr = top;
             while (curr != null) {
                 System.out.print(curr.getItem() + " ");
                 curr = curr.getNext();
             }
             System.out.println();
         }
     public
         void bubbleSort()
         {
             Node curr = top;
             Node prev = null;
             int temp = 0;
             while (curr.getNext() != null) {
                 prev = top;
                 while (prev.getNext() != null) {
                     // If previous item is greater than current
                     if (prev.getItem() > prev.getNext().getItem()) {
                         temp = prev.getItem();
                         // Make the swap
                         prev.setItem(prev.getNext().getItem());
                         prev.getNext().setItem(temp);
                     }
                     prev = prev.getNext();
                 }
                 curr = curr.getNext();
             }
         }
     }
 } 

Output:

 Before sorting: 20 30 40 10
 After sorting: 10 20 30 40 

Time complexity: O(n*n)


Related Topics

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.

DAA: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.