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: 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: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

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.

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.

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.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 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.

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: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

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 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...

4 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.

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: 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.

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: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 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: 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.