JavaScript
Array
Sort
Algorithm
Programming

Javascript Array.sort implementation?

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

JavaScript's Array.sort is a built-in method that allows arrays to be sorted in a defined order. Although it is widely used, the underlying mechanism can sometimes be a black box, especially when unexpected behavior occurs. This article delves into the technical details of [Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), including its typical implementation and considerations.

Default Behavior of Array.sort()

By default, Array.sort() sorts elements as strings. If the elements should be sorted in a different manner (such as numerically), a compare function must be provided. Here's the standard syntax:

javascript
array.sort([compareFunction])

Example of Default Sorting

Consider the following example:

javascript
const fruits = ['banana', 'apple', 'mango'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'mango']

Now consider an array of numbers:

javascript
const numbers = [25, 3, 54];
numbers.sort();
console.log(numbers); // Output: [25, 3, 54]

The above output may seem counterintuitive as the numbers aren't sorted numerically. Since Array.sort treats each number as a string, it alphabetically compares the Unicode values of the characters.

Implementing a Compare Function

To sort numbers, a compare function is needed:

javascript
const numbers = [25, 3, 54];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [3, 25, 54]

The Compare Function Structure

The compareFunction should return:

  • A negative value if the first argument should be sorted before the second.
  • Zero if the two items should be treated as equal.
  • A positive value if the first argument should be sorted after the second.

Here's an example using strings with varied criteria:

javascript
1const items = [
2  { name: 'apple', quantity: 2 },
3  { name: 'banana', quantity: 10 },
4  { name: 'mango', quantity: 5 },
5];
6
7items.sort((a, b) => a.quantity - b.quantity);
8console.log(items);
9// Output:
10// [
11//   { name: 'apple', quantity: 2 },
12//   { name: 'mango', quantity: 5 },
13//   { name: 'banana', quantity: 10 }
14// ]

Stability of Array.sort()

ECMAScript 2019 standardized the behavior of Array.sort to be stable. A sort is considered stable if it preserves the relative order of items that evaluate as equivalent. For instance:

javascript
const items = ['peach', 'strawberry', 'apple'];
items.sort((a, b) => a.length - b.length);
console.log(items); // Output: ['apple', 'peach', 'strawberry']

Here, "peach" and "apple" both have five letters and their relative order is preserved.

Sorting Algorithms Used

The algorithm employed by Array.sort can vary between JavaScript engines and is not explicitly defined by ECMAScript, but several engines have common practices:

  • V8 (Google Chrome & Node.js): Uses TimSort, a hybrid sorting algorithm based on Merge Sort and Insertion Sort.
  • SpiderMonkey (Mozilla Firefox): Uses Merge Sort.
  • JavaScriptCore (Safari): Also uses TimSort.

TimSort Characteristics

Incorporated by many JavaScript engines, TimSort has the following features:

  • Time Complexity: O(n log n) in the average and worst cases.
  • Space Complexity: O(n), due to auxiliary data structures used.
  • Stability: Sorted order of equal elements is preserved.

Performance Considerations

Sorting can be computationally intensive, and for very large arrays, performance might become a concern. It is helpful to consider the complexity of the compare function and evaluate possible optimizations. Furthermore, for specific high-efficiency requirements, it can be beneficial to explore writing a custom sort function with optimized algorithms like QuickSort, HeapSort, or even utilizing WebAssembly.

Summary Table

Here's a quick overview of key points regarding JavaScript's Array.sort:

FeatureDescription
Default BehaviorSorts array items as strings (lexicographically).
StabilityDefined as stable from ECMAScript 2019 onwards.
Default AlgorithmTimSort in V8 MergeSort in SpiderMonkey TimSort in JavaScriptCore
Time ComplexityTypically O(n log n)
Space ComplexityO(n)
Custom CompareNeeded for different sorting criteria (e.g., numbers, objects).

In conclusion, understanding the intricacies of Array.sort, along with its algorithm and behavior, allows for more effective and intentional use in applications. With these insights, developers can optimize and tailor array sorting operations to meet specific use cases.


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.