Skip to main content

Intro to Sorting Algorithms

What is Sorting?

Sorting is the process of arranging data in a specific order — either ascending or descending. It is one of the most fundamental operations in computer science, forming the foundation for efficient searching, data processing, and algorithm design.

Example — ascending sort:

30
idx 0
10
idx 1
20
idx 2
5
idx 3
5
idx 0
10
idx 1
20
idx 2
30
idx 3

Types of Sorting Algorithms

1. Comparison-Based Sorting

Sort by comparing elements with each other. Lower bound: O(n log n)

  • Bubble Sort — repeatedly swaps adjacent elements
  • Insertion Sort — inserts each element into its correct position
  • Selection Sort — selects the minimum and places it at the front
  • Merge Sort — divide and conquer, always O(n log n)
  • Quick Sort — pivot-based partitioning, O(n log n) average

2. Non-Comparison Based Sorting

Sort without direct comparisons — can achieve O(n) time

  • Counting Sort — count occurrences, O(n + k)
  • Radix Sort — sort digit by digit, O(nk)

3. Hybrid Algorithms

Combine strategies for optimal real-world performance

  • Timsort — Merge Sort + Insertion Sort (Python, Java built-in)
  • Introsort — Quick Sort + Heap Sort (C++ STL built-in)

Key Concept: In-Place Sorting

A sorting algorithm is in-place if it sorts using O(1) extra space — it modifies the original array without allocating an extra copy.

In-place: Bubble Sort, Selection Sort, Insertion Sort

NOT in-place: Merge Sort — requires O(n) auxiliary space for temp arrays

# Bubble Sort -- in-place, no extra array needed
arr = [3, 1, 2]
# [1, 3, 2] --> [1, 2, 3]   Only swaps within arr itself

Key Concept: Stable Sorting

A sorting algorithm is stable if elements with equal keys maintain their original relative order after sorting.

# Example: Sort students by marks
Original:  [(Alice, 80), (Bob, 90), (Charlie, 80)]

Stable sort by marks:
--> [(Alice, 80), (Charlie, 80), (Bob, 90)]   Alice still before Charlie

Unstable sort might give:
--> [(Charlie, 80), (Alice, 80), (Bob, 90)]   Relative order changed!

Algorithm Comparison Table

AlgorithmStable?In-Place?BestAverageWorst
Bubble Sort✅ Yes✅ YesO(n)O(n²)O(n²)
Insertion Sort✅ Yes✅ YesO(n)O(n²)O(n²)
Selection Sort❌ No✅ YesO(n²)O(n²)O(n²)
Merge Sort✅ Yes❌ NoO(n log n)O(n log n)O(n log n)
Quick Sort❌ No✅ YesO(n log n)O(n log n)O(n²)

Explore Each Algorithm