Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Program for Sorting a Linked List of 0s, 1s, And 2s
In this tutorial, we will learn the JavaScript program for sorting a linked list of 0s, 1s, and 2s. Sorting algorithms are essential for any programming language, and JavaScript is no exception. Sorting a linked list of 0s, 1s, and 2s is a common problem that developers encounter in coding interviews and real-world applications.
So, let's dive in and explore how to sort a linked list of 0s, 1s, and 2s using JavaScript programming.
What is Sorting?
Sorting is the process of arranging elements in a specific order, either ascending or descending. It is a fundamental operation in computer science and has numerous applications in real-world scenarios. Sorting algorithms are used to organize data for efficient search, reduce redundancy, and optimize space and time complexity.
Here are some examples of sorting in JavaScript:
Example 1 ? Sorting an array of numbers in ascending order:
Input: arr = [5, 3, 8, 1, 2, 9] Output: [1, 2, 3, 5, 8, 9]
Example 2 ? Sorting an array of strings in alphabetical order:
Input: ['apple', 'banana', 'orange', 'grape'] Output: ['apple', 'banana', 'grape', 'orange']
What is a Linked List?
A linked list is a linear data structure consisting of nodes that are linked together by pointers. Each node contains a data element and a reference to the next node in the list. Linked lists are commonly used for dynamic data structures, where the size of the data changes frequently.
Problem Statement
The objective is to arrange and display a linked list comprising 0s, 1s, and 2s in an ordered sequence. This problem is also known as the "Dutch National Flag" problem for linked lists.
Examples
Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL
Algorithm for Sorting Linked List of 0s, 1s, and 2s
The steps for sorting a linked list of 0s, 1s, and 2s using the counting sort algorithm:
STEP 1 ? Define a function sortList(head) which takes the head of the linked list as input.
STEP 2 ? Initialize a count array count[] of size 3 with all elements as 0.
STEP 3 ? Traverse the linked list and increment the count of the node data at the corresponding index in the count array.
STEP 4 ? Traverse the linked list again and replace the node data with the lowest index value for which the count is greater than 0.
STEP 5 ? Decrement the count of the node data for each replacement.
STEP 6 ? Print the linked list before and after sorting.
Example: Counting Sort Approach
The below JavaScript program uses a counting sort algorithm to sort a linked list containing 0s, 1s, and 2s. The algorithm first counts the frequency of 0s, 1s, and 2s in the list, then updates the values of nodes in the list based on the count of each value.
/* Link list node */
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
// Add new node at the beginning
push(new_data) {
const new_node = new Node(new_data);
new_node.next = this.head;
this.head = new_node;
}
// Print the linked list
printList() {
let currentNode = this.head;
let value = "";
while (currentNode !== null) {
value += currentNode.data + " -> ";
currentNode = currentNode.next;
}
console.log(value + "NULL");
}
// Sort the linked list of 0s, 1s and 2s
sortList() {
const count = [0, 0, 0]; // Initialize count of '0', '1' and '2' as 0
let ptr = this.head;
// Count occurrences of 0, 1, and 2
while (ptr !== null) {
count[ptr.data] += 1;
ptr = ptr.next;
}
// Update data values based on count
ptr = this.head;
let i = 0;
while (ptr !== null) {
if (count[i] === 0) {
++i;
} else {
ptr.data = i;
--count[i];
ptr = ptr.next;
}
}
}
}
// Create linked list and test
const linkedList = new LinkedList();
linkedList.push(0);
linkedList.push(1);
linkedList.push(0);
linkedList.push(2);
linkedList.push(1);
linkedList.push(1);
linkedList.push(2);
linkedList.push(1);
linkedList.push(2);
console.log("Before sorting:");
linkedList.printList();
linkedList.sortList();
console.log("After sorting:");
linkedList.printList();
Before sorting: 2 -> 1 -> 2 -> 1 -> 1 -> 2 -> 0 -> 1 -> 0 -> NULL After sorting: 0 -> 0 -> 1 -> 1 -> 1 -> 1 -> 2 -> 2 -> 2 -> NULL
How It Works
The counting sort approach works in two phases:
- Count Phase: Traverse the linked list once and count the occurrences of 0s, 1s, and 2s.
- Update Phase: Traverse the linked list again and update each node's data based on the counts, filling 0s first, then 1s, and finally 2s.
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time Complexity | O(n) | Two traversals of the linked list |
| Space Complexity | O(1) | Only uses fixed-size count array of 3 elements |
Key Points
- The counting sort approach is optimal for this specific problem since we only have three distinct values (0, 1, 2).
- The algorithm maintains the original linked list structure without creating a new list.
- This solution works in linear time with constant space complexity.
- The approach is stable and handles duplicate values correctly.
Conclusion
The counting sort technique provides an efficient O(n) time solution for sorting a linked list containing only 0s, 1s, and 2s. This approach leverages the limited range of values to achieve optimal performance with constant space complexity.
