JavaScript Notes
Master sorting algorithms in JavaScript: Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, and Quick Sort. Learn time complexity, visualizations, implementations, and interview Q&A.
Sorting is one of the most fundamental operations in computing. Understanding how different algorithms sort — and their time/space tradeoffs — is essential for writing performant code and acing technical interviews.
💡 Key insight: JavaScript's built-in Array.sort() uses TimSort (merge sort + insertion sort hybrid), which is O(n log n) and stable. Understanding the underlying algorithms explains *when* and *why* to choose them.Algorithm Comparison
| Algorithm | Best | Average | Worst | Space | Stable? |
|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | ✅ |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | ❌ |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | ✅ |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | ✅ |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | ❌ |
JS Array.sort() | O(n) | O(n log n) | O(n log n) | O(n) | ✅ |
JavaScript Built-in Array.sort()
[1, 10, 2, 21, 9] // WRONG — lexicographic [1, 2, 9, 10, 21] // correct ascending [21, 10, 9, 2, 1] // correct descending ["apple", "banana", "cherry", "date"] ["apple", "banana", "cherry", "date"] ["Alice", "Bob", "Charlie"]
1. Bubble Sort — O(n²)
[1, 2, 3, 5, 8]
2. Insertion Sort — O(n²), great for small/nearly sorted arrays
[1, 2, 3, 5, 8, 9]
3. Merge Sort — O(n log n), stable
[1, 2, 3, 5, 8, 9]
4. Quick Sort — O(n log n) average, O(n²) worst
[1, 2, 3, 5, 8, 9]
When to Use Which Algorithm
| Scenario | Best Choice |
|---|---|
| General purpose | Array.sort() (TimSort) |
| Small array (< 20 elements) | Insertion Sort |
| Nearly sorted data | Insertion Sort |
| Need stable sort | Merge Sort |
| Memory limited | Quick Sort / Heap Sort |
| Linked list sorting | Merge Sort (no random access needed) |
| Learning / interviews | Bubble Sort (simple to explain) |
Common Mistakes
- Not providing a comparator to
Array.sort()— default sort converts elements to strings.[10,9,1].sort()gives[1,10,9], not[1,9,10]. - Mutating the original array —
Array.sort()sorts in-place. Clone first:[...arr].sort(...). - Quick Sort worst case — if the pivot is always the smallest or largest (e.g., already sorted array with first-element pivot), quick sort degrades to O(n²). Use a random or median-of-three pivot.
- Assuming stability —
Array.sort()is stable in modern JS engines (V8, SpiderMonkey), but always confirm when relying on stable behaviour.
Interview Questions
Q1. What is the time complexity of Merge Sort?
O(n log n) in all cases (best, average, worst). It always divides the array in half and merges — there's no bad pivot or early-exit case. Space complexity is O(n) for the auxiliary arrays during merge.
Q2. Why is Quick Sort generally faster than Merge Sort in practice?
Quick Sort has better cache performance (in-place, operates on contiguous memory) and lower constant factors than Merge Sort (which requires allocating new arrays during merge). Average case is O(n log n) for both, but Quick Sort's cache behaviour wins in practice.
Q3. What does "stable sort" mean?
A stable sort preserves the relative order of equal elements. If two items compare as equal, a stable sort keeps them in the same relative order as they appeared in the input. JavaScript's Array.sort() is stable in all modern engines (guaranteed since ECMAScript 2019).Q4. What is the default sort behaviour of Array.sort()?
Without a comparator,Array.sort()converts elements to strings and sorts lexicographically. This is correct for string arrays but wrong for numbers:[10, 9, 2].sort()gives[10, 2, 9].
Q5. How does Insertion Sort achieve O(n) on a nearly sorted array?
Each element is compared with those before it. If data is nearly sorted, each element moves only a few positions, resulting in near-linear comparisons total.
Q6. What is TimSort?
TimSort is a hybrid sorting algorithm combining Insertion Sort (for small runs) and Merge Sort (for merging those runs). It achieves O(n) for already-sorted data and O(n log n) worst case. It's stable and is used in JavaScript, Python, and Java's Arrays.sort for objects.Q7. What comparator do you pass to Array.sort() to sort numbers correctly?
arr.sort((a, b) => a - b)for ascending order. Ifa - bis negative,acomes first; if positive,bcomes first; if 0, order is unchanged.
Key Takeaways
- Always pass a comparator to
Array.sort()for numbers — default is lexicographic. - Merge Sort is O(n log n) guaranteed and stable — best for linked lists and when stability matters.
- Quick Sort is O(n log n) average but O(n²) worst case — choose a good pivot.
- Insertion Sort is O(n) for nearly-sorted data and great for small arrays.
- JavaScript's built-in
Array.sort()uses TimSort — O(n log n), stable, very efficient. Array.sort()mutates the original array — clone first if you need the original.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Sorting Algorithms in JavaScript — Bubble, Merge, Quick Sort Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, data, structures, sorting
Related JavaScript Master Course Topics