šŸŒ‡DSA
← Back
AlgorithmBeginner
šŸ“Š

Sorting Algorithms

Arrange data in order

ā±ļø 6–10 hours🧩 10 LeetCode
šŸ”’ Login to unlock solutions and track progress. Login

What is it?

Sorting means putting things in order — like arranging books on a shelf from A to Z, or ranking students by score.

Different algorithms trade off speed, memory, and stability (whether equal items keep their original order).

Algorithm Comparison

| Algorithm | Best | Average | Worst | Space | Stable | |----------------|------------|------------|------------|----------|--------| | Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | āœ… Yes | | Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | āœ… Yes | | Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | āœ… Yes | | Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | āŒ No | | Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | āŒ No |

Real-World Examples

Products sorted by price
Search results by relevance
Messages by timestamp
Leaderboard rankings
Database ORDER BY
File explorer sort

Code Example

What this code shows

Merge sort splits [3,1,4,1,5,9,2] into single-element halves (already sorted), then merges them back together in order — always comparing the front of the left and right half and picking the smaller one.

function mergeSort(arr) {
// base case: a single item is already sorted
if (arr.length <= 1) return arr;

const mid = Math.floor(arr.length / 2);
const left  = mergeSort(arr.slice(0, mid)); // sort left half
const right = mergeSort(arr.slice(mid));    // sort right half

// merge two sorted halves into one sorted array
const result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
  // always pick the smaller front element
  result.push(left[i] <= right[j] ? left[i++] : right[j++]);
}
// append any remaining elements
return result.concat(left.slice(i), right.slice(j));
}

console.log(mergeSort([3, 1, 4, 1, 5, 9, 2]));
// [1, 1, 2, 3, 4, 5, 9]

Expected Output

[1, 1, 2, 3, 4, 5, 9]

LeetCode Practice