Time complexity of O(n^2) sorts
What you'll learn: Why basic sorting algorithms like Bubble, Insertion, and Selection sort slow down drastically as your data grows.
The "Double-Loop" Problem
When you write a basic sorting algorithm, you almost always use two nested loops. The outer loop keeps track of how many items you’ve sorted, while the inner loop compares the current item against the rest of the list.
In computer science, we call this O(n²) complexity (pronounced "Big O of n-squared"). The n represents the number of items in your array. If you have 10 items, you might perform roughly operations. If you have 100 items, you perform .
A Concrete Analogy: Dealing Cards
Imagine you are sorting a hand of playing cards.
- If you have 5 cards, you can sort them in seconds.
- If you have 50 cards, it takes significantly longer, but you can still do it at your desk.
- If you have 5,000 cards, using the same "pick one and compare it to every other card" method would take you hours.
The workload doesn't grow in a straight line; it grows like a square. When you double the amount of data, the time it takes to sort doesn't just double—it quadruples.
What this looks like in C
In algorithms like Selection Sort, the nested structure is very visible. Notice how for every single pass of the i loop, the j loop must run through the remaining elements.
#include <stdio.h>
void selectionSortExample(int arr[], int n) {
int i, j, min_idx;
// Outer loop: Runs 'n' times
for (i = 0; i < n - 1; i++) {
min_idx = i;
// Inner loop: Also runs roughly 'n' times
// This nesting is what creates the n * n (n^2) complexity
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
Why it matters
O(n²) algorithms are perfectly fine for small arrays (like 50 or 100 elements) because they are simple to write and have very little "overhead." However, if you try to use Bubble or Selection sort on a database of 1,000,000 users, your program might take hours—or even days—to finish a task that more advanced algorithms could do in less than a second.
Key takeaway
O(n²) algorithms are "quadratic," meaning their execution time grows exponentially relative to the input size because of nested loops.