Skip to content

Sorting Algorithm

In one line

A sorting algorithm rearranges elements of a collection into a defined order (ascending, descending, or custom).

In simple words

A sorting algorithm takes a collection of items and rearranges them into order — numerical, alphabetical, or by any comparison function. Sorting is one of the most studied problems in computer science because ordered data is easier to search, display, and analyze.

Common algorithms include bubble sort (simple but O(n²)), insertion sort (good for small or nearly-sorted data), merge sort (O(n log n), stable, divides and conquers), quick sort (O(n log n) average, in-place, widely used), and heap sort (O(n log n), in-place, not stable). Each makes different trade-offs between speed, memory, stability, and worst-case behavior.

Most languages provide a built-in sort that uses a highly tuned hybrid algorithm (like Timsort in Python and V8, which combines merge sort and insertion sort). You rarely write your own sort in production, but understanding how they work is essential for interviews and for choosing the right approach when built-in sort is not suitable.

Example

javascript
// Quick sort — divide and conquer
function quickSort(arr) {
  if (arr.length <= 1) return arr;
  const pivot = arr[0];
  const less = arr.slice(1).filter(x => x < pivot);
  const more = arr.slice(1).filter(x => x >= pivot);
  return [...quickSort(less), pivot, ...quickSort(more)];
}

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

Quick sort picks a pivot, partitions the rest into less/more, and recursively sorts each partition. Average O(n log n).

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary