JavaScript
Sorting Algorithm
Stable Sort
Fast Implementation
Programming

Fast stable sorting algorithm implementation in javascript

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In the world of sorting algorithms, stability is a crucial property that ensures equivalent elements retain their original relative order after sorting. Implementing a stable sorting algorithm efficiently in JavaScript can be vital for tasks that require an order-preserving sort, such as sorting objects based on multiple keys or maintaining the order of equal elements based on their initial positions in a dataset.

Overview of Sorting Algorithms

Sorting algorithms can be divided into stable and unstable categories:

  • Stable Sorts: Maintain the relative order of records with equal keys (e.g., Merge Sort, Timsort).
  • Unstable Sorts: Do not maintain the relative order of records with equal keys (e.g., Quick Sort, Heap Sort).

JavaScript, following the ECMAScript specification, uses Timsort, a hybrid stable sorting algorithm derived from Merge Sort and Insertion Sort for the .sort() method on arrays. This ensures that JavaScript natively supports stable sorting.

Implementing a Fast Stable Sort

One efficient algorithm for stable sorting is the Merge Sort algorithm. In this section, we'll implement a stable Merge Sort in JavaScript.

Understanding Merge Sort

Merge Sort is a divide-and-conquer algorithm that:

  1. Divides the array into two halves.
  2. Recursively sorts the halves.
  3. Merges the sorted halves to produce a single sorted array.

Implementation Example

Below is a JavaScript implementation of a stable Merge Sort:

javascript
1function mergeSort(arr) {
2  if (arr.length <= 1) return arr;
3
4  const mid = Math.floor(arr.length / 2);
5  const leftArr = mergeSort(arr.slice(0, mid));
6  const rightArr = mergeSort(arr.slice(mid));
7
8  return merge(leftArr, rightArr);
9}
10
11function merge(left, right) {
12  const result = [];
13  let leftIndex = 0;
14  let rightIndex = 0;
15
16  while (leftIndex < left.length && rightIndex < right.length) {
17    if (left[leftIndex] <= right[rightIndex]) {
18      result.push(left[leftIndex]);
19      leftIndex++;
20    } else {
21      result.push(right[rightIndex]);
22      rightIndex++;
23    }
24  }
25
26  return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
27}
28
29const array = [5, 3, 8, 4, 2];
30const sortedArray = mergeSort(array);
31console.log(sortedArray); // Output: [2, 3, 4, 5, 8]

How the Algorithm Works

  1. Recursive Splitting: The mergeSort function splits the array recursively until it can no more be split (base case: array of length 1 or empty).
  2. Merging: The merge function takes two sorted arrays and combines them into one while maintaining order.

Performance Analysis

  • Time Complexity: O(nlogn)O(n \log n) in all cases, where nn is the number of elements in the array.
  • Space Complexity: O(n)O(n) due to the auxiliary arrays used in merging.

Summary Table

Here's a summary of the properties for the Merge Sort implementation:

PropertyDescription
StabilityYes - original order for equal items is preserved
Time ComplexityO(nlogn)O(n \log n) in best, average, and worst cases
Space ComplexityO(n)O(n) - additional memory required for merging
RecursiveYes
ParallelizableYes, the divide step can be parallelized

Enhancements and Considerations

Stability Importance

  • Maintaining Original Order: Stable sorting is essential in scenarios requiring order preservation, such as when dealing with complex data structures or multiple key sorting.

Optimizations

  • Insertion Sort for Small Arrays: For smaller subarrays, switching to a simpler algorithm like Insertion Sort might improve performance.
  • Timsort: Combining Merge Sort logic with Insertion Sort, Timsort is the algorithm behind JavaScript's native .sort() method, providing optimized real-world performance.

Conclusion

Stable sorting is an essential tool in any programmer's toolkit for dealing with ordered data. The Merge Sort algorithm, with its stability and efficiency, is a reliable choice for implementing order-preserving sorts in JavaScript. Understanding these concepts helps developers solve complex problems like multi-key sorting and reinforces the knowledge of algorithm design and analysis.

By leveraging modern JavaScript features and understanding how the language's native sorting works, developers can write performant code that respects the data's intrinsic order, making Merge Sort an invaluable asset.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.