QuickSort on Singly Linked List

Introduction

The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.

Problem Statement

According to the problem statement, We will be given a singly linked list and we need to sort the list using Quick sort sorting algorithm.

Before going to the approach section, we need to understand Quicksort Algorithm thoroughly. It is easier to understand the QuickSort algorithm on an array; that’s why we will first learn to apply quicksort on an array, and then learn how to apply the Quicksort algorithm on a singly linked list.

Introduction - Quick Sort

  • QuickSort is a Divide and Conquer algorithm, so it is also a recursive algorithm.
  • Here, We pick an element as a pivot and partition the given array around the picked pivot element.
  • After partition, we arrange the elements such that all the elements smaller than the pivot element will be before the pivot, and all the elements greater than the pivot element will be after the pivot.
  • After this, we will call Quick sort again on the elements from starting to pivot-1 and pivot+1 to the end.
  • We will continue to call Quick sort till we hit the base case.

Algorithm (Quick Sort)

  • We have to first pick an element of the array as a pivot.
  • We can choose any element as a pivot element, e.g. starting element of the array, last element of the array, middle element of the array, etc.
  • We will take the first element of the array as the pivot element.
  • Now we will count the number of elements that are smaller than the pivot element in the array.
  • Now we have to move the pivot element to its correct position in the array.
  • Initialize K = 0, K is the correct position of the pivot element.
    • K = (pivot index + the number of elements smaller than the pivot element in the array).
  • After swapping the pivot element with the element at the index K, arrange the elements such that all elements smaller than the pivot element will be before the pivot, and all elements greater than the pivot element will be after the pivot.
  • After this, we will call Quicksort again on the elements from starting index to pivot-1 and pivot+1 to the end index. We will continue to call Quicksort till we hit the base case.

Dry Run

Code Implementation

#include
using namespace std;

int partition(int* arr, int si, int ei){

    int count = 0;
    // count of numbers of elements smaller than arr[0]

    int i = si+1;
    while(i<=ei){
        if(arr[i]pivot){
        if(arr[k]>arr[pivot] && arr[j]arr[pivot]){
            j--;
        }
    }

    return pivot;
}


void quickSort(int* arr, int si, int ei){
    //Base case
    if(si>=ei){
        return;
    }


    // function for partition around pivot
    int pivot = partition(arr, si, ei);

    quickSort(arr, si, pivot-1);
    quickSort(arr, pivot+1, ei);
}

int main(){
    int n;
    cin>>n;

    int* arr = new int[n];

    for(int i=0; i>arr[i];
    }

    quickSort(arr, 0, n-1);

    for(int i=0; i

						 

Now, we have a good understanding of the QuickSort algorithm. Let’s learn how to apply QuickSort on a singly linked list.

Algorithm

Quick Sort on Singly Linked List:

Initialize a pointer named tail of type node with head, and move it to the last node of the linked list. To get the last node of the linked list, we will traverse through the list until we have found a node whose next is NULL.

Recursive Function: Node quickSortHelper( Node head, Node *tail), it will return the new head after sorting the list.

Base Case: When the head and tail point to the same node or head is NULL, we will just return the head.

Algorithm Steps:
1) We can pick any element as a pivot, but we will pick the last element as a pivot.
2) Make a partition function that will partition the list around the picked pivot.
3) We have already seen that we need to arrange the elements such that all elements smaller than the pivot element will be before the pivot, and all elements greater than the pivot element will be after the pivot; that’s why we will create a partition function.
4) In this partition function, we will traverse through the current list, and :

  • If a node’s data is greater than the pivot’s data, we move it after tail.
  • Else if the node’s data has a smaller value than the tail’s data, we keep it at its current position, i.e, no change in position.
    5) In this partition function, after partition of the nodes around the pivot node, generates two new linked lists. One linked list contains all nodes that are smaller in value than the pivot node and another linked list contains all nodes greater than the pivot node.
    6) The partition function will update 5 pointers that point to the pivot, head and tail pointer of linked list containing all nodes smaller than pivot and head and tail pointer of linked list containing all nodes greater than pivot.
    7) Now we will call quickSortRecur on nodes that are smaller than the pivot node, after that we will again call quickSortRecur on nodes that are greater than the pivot node.
    8) This process continues till we hit the base case and when we hit the base case we start returning from the recursive calls.
    9) When we return back after hitting the base case we will join these two linked lists in such order that our whole linked list remains sorted.

Dry Run

Code Implementation

#include 
using namespace std;

/* Node structure of a singly linked list */
class Node {
public:
    int data;
    Node* next;
};

/* Using this function we will insert a node at the beginning of the linked list */
void push(Node** head_ref, int val){
    Node* newNode = new Node;

    newNode->data = val;

    newNode->next = (*head_ref);

    (*head_ref) = newNode;
}

/* Using this function we will print the content of the linked list */
void printList(Node* node){
    while (node != NULL) {
        cout<data<<" ";
        node = node->next;
    }
    cout<next != NULL)
        cur = cur->next;
    return cur;
}

/* Using this function we will partition the linked list taking the last element of list as pivot */
Node* partition( Node* head,  Node* end,
                     Node** newHead,
                     Node** newEnd)
{
     Node* pivot = end;
     Node *prev = NULL, *cur = head, *tail = pivot;

    // During the time of partition, both the head and end of the list
    // might change and the changes will be updated in the newHead and
    // newEnd variables
    while (cur != pivot) {
        if (cur->data < pivot->data) {
            // The first node that will be having value less than the
            // pivot node value will become the new head
            if ((*newHead) == NULL)
                (*newHead) = cur;

            prev = cur;
            cur = cur->next;
        }
        else // If the value of the cur node is greater than that of the pivot
        {
            // We will move the cur node to next of tail, and will update tail
            if (prev)
                prev->next = cur->next;
             Node* tmp = cur->next;
            cur->next = NULL;
            tail->next = cur;
            tail = cur;
            cur = tmp;
        }
    }

    // If the data of the pivot node is smallest in the
    // current list, then we will make pivot as the head
    if ((*newHead) == NULL)
        (*newHead) = pivot;

    // newEnd will be updated to the current last node
    (*newEnd) = tail;

    // Finally, we will return the pivot node
    return pivot;
}

// Quick sort recursive function
 Node* quickSortRecur( Node* head,
                             Node* end)
{
    // base condition
    if (!head || head == end)
        return head;

    Node *newHead = NULL, *newEnd = NULL;

    // We will call the partition function and it will partition the list
    // and will also update newHead and newEnd
    // it will return the pivot node
     Node* pivot
        = partition(head, end, &newHead, &newEnd);

    // If our pivot is the smallest element in the current list
    // then there is no need to recur for the left part of the list
    if (newHead != pivot) {
         Node* tmp = newHead;
        while (tmp->next != pivot)
            tmp = tmp->next;
        tmp->next = NULL;

        // Now we will recur for the list before the pivot
        newHead = quickSortRecur(newHead, tmp);

        tmp = getTail(newHead);
        tmp->next = pivot;
    }

    // Now we will recur for the list after the pivot
    pivot->next = quickSortRecur(pivot->next, newEnd);

    return newHead;
}

// Ths is the function for quicksort. 
void quickSort(Node** headRef){
    (*headRef)
        = quickSortRecur(*headRef, getTail(*headRef));
    return;
} 


int main(){
    Node* a = NULL;
    push(&a, 8);
    push(&a, 9);
    push(&a, 5);
    push(&a, 3);
    push(&a, 2);
    push(&a, 7);


    cout << "Linked List before sorting \n";
    printList(a);

    quickSort(&a);

    cout << "Linked List after sorting \n";
    printList(a);

    return 0;
}

Output

Linked List before sorting
7 2 3 5 9 8
Linked List after sorting
2 3 5 7 8 9

Time Complexity: Best case - O(NlogN), Worst case - O(N2).

So, In this blog, we have learned How to QuickSort on Singly Linked List. This is an important question when it comes to coding interviews. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.

Previous post Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
Next post Subtract two numbers represented as Linked Lists

Leave a Reply

Your email address will not be published. Required fields are marked *