Sorting

Welcome to the Sorting section of JDCodebase! Sorting is a fundamental concept in computer science. It not only helps organize data but also optimizes searching, comparisons, and problem-solving techniques like binary search or greedy strategies.

What You’ll Learn

  • Different types of sorting algorithms and their trade-offs
  • Built-in vs custom sorting logic in JavaScript
  • When to use stable vs unstable sorts
  • Combine sorting with searching or two-pointer techniques
  • Time complexity analysis of common sorting algorithms

JavaScript Sorting Methods

arr.sort(): Sorts elements in place as strings by default.
Before: [3, 1, 20]
Code: arr.sort();
After: [1, 20, 3] // lexicographic sort
arr.sort((a, b) => a - b): Sorts numerically in ascending order.
Before: [3, 1, 20]
Code: arr.sort((a, b) => a - b);
After: [1, 3, 20]
arr.sort((a, b) => b - a): Sorts numerically in descending order.
Before: [3, 1, 20]
Code: arr.sort((a, b) => b - a);
After: [20, 3, 1]

Try This Example

Sort an array of numbers in ascending order.

function sortAscending(arr) {
    return arr.sort((a, b) => a - b);
  }

Input: [5, 2, 8, 1]

Expected Output: [1, 2, 5, 8]

📚 Common Sorting Algorithms

Here are some popular sorting algorithms you may implement manually in interviews or competitive coding:

Sorting Algorithms Overview

  • **Bubble Sort** — Repeatedly swaps adjacent elements. Simple but inefficient (O(n²)).
  • **Selection Sort** — Selects the smallest/largest and moves it into place. O(n²).
  • **Insertion Sort** — Builds the sorted array one item at a time. Great for small or mostly sorted arrays. O(n²).
  • **Merge Sort** — Divide-and-conquer. Stable, reliable O(n log n).
  • **Quick Sort** — Partition-based. Fast in practice, avg O(n log n), worst-case O(n²).
  • **Counting Sort** — Efficient for small-range integers. O(n + k), not comparison-based.