DSA Basics: Sorting

Learn why sorting changes problem difficulty and compare common sorting algorithms.

Back to Learn DSA

Sorting arranges values in a useful order. Many problems become easier after sorting because relationships become predictable.

For example, after sorting an array, two pointers can move inward to solve pair-sum problems efficiently.

Common sorting algorithms

Bubble sort

Bubble sort repeatedly swaps adjacent values that are out of order. It is easy to understand but slow for large inputs.

Time complexity: O(n²).

Selection sort

Selection sort repeatedly finds the smallest remaining value and moves it into position.

Time complexity: O(n²).

Merge sort

Merge sort splits the array, sorts both halves, then merges them.

Time complexity: O(n log n).

Quick sort

Quick sort picks a pivot and partitions values around it.

Average time complexity: O(n log n).

JavaScript sorting warning

JavaScript’s default .sort() converts values to strings unless you provide a comparator.

[10, 2, 5].sort(); // [10, 2, 5] as string order
[10, 2, 5].sort((a, b) => a - b); // [2, 5, 10]

When sorting helps

Practice problems

  1. Sort numbers ascending.
  2. Merge two sorted arrays.
  3. Remove duplicates from a sorted array.
  4. Find the minimum number of meeting rooms.
  5. Sort intervals and merge overlaps.

Interactive walkthrough

Sorting Visualizer

Compare, move, and settle values into order.
Step 1 compare
Step 2 swap
Step 3 partition
Step 4 merge