Before learning any sorting algorithm, it helps to know why sorting matters so much, and how programmers tell one sorting algorithm from another.
Sorting is one of the most common jobs a program does. Your phone sorts contacts from A to Z, a shopping site sorts products by price, and a results page sorts students by marks. Behind each of these is a sorting algorithm.
By the end of this lesson, you will understand:
- What sorting is
- Why programs sort data
- The words used to describe sorting algorithms: stable, in-place, adaptive and more
- How the six algorithms in this chapter compare
- How to sort using each language's built-in tools
What Is Sorting?
Sorting means arranging items in a particular order. Usually that is:
- Ascending: smallest to largest, like
1, 2, 4, 5, 8, or A to Z - Descending: largest to smallest, like
8, 5, 4, 2, 1, or Z to A
You can sort anything that can be compared: numbers, names, dates, prices, even students by their marks.
before sorting: 72 85 9 100 64
after sorting: 9 64 72 85 100
Why Do We Sort?
1. Searching Becomes Much Faster
Remember binary search from the Big-O lesson? It finds a name in a list of 100,000 (1 lakh) students in about 17 steps, by repeatedly throwing away half the list. Checking one by one could take 100,000 steps. But binary search only works if the list is sorted.
2. Duplicates and Close Values Sit Together
Once data is sorted, equal values end up next to each other. Finding duplicate roll numbers, or the two closest prices, becomes a single walk through the list.
3. Ranking and Top Lists
The top 10 students, the cheapest flights, the newest messages: all of these are just the first few items of a sorted list.
4. Data People Can Read
Contacts from A to Z, files by date, a leaderboard by score. Sorted data is simply easier for humans to use.
5. A Building Block for Other Algorithms
Many algorithms you'll meet later, such as finding the median or merging two lists, start by sorting the data first.
Sorting With Built-In Tools
Every language already has a sort built in. In real projects you'll usually use it, because it is fast and well tested. Here is how:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] marks = {72, 85, 9, 100, 64};
Arrays.sort(marks); // smallest to largest
System.out.println(Arrays.toString(marks)); // [9, 64, 72, 85, 100]
}
}A classic JavaScript trap. Without a comparison function,
sort()turns numbers into text and sorts them alphabetically, so"100"comes before"64"because1comes before6. Always pass(a, b) => a - bwhen sorting numbers.
In C, notice the comparison function returns (x > y) - (x < y) instead of the shorter x - y. With very large or very negative numbers, x - y can overflow and give the wrong answer.
So why learn sorting algorithms at all? Because each one teaches a way of thinking about problems: swapping neighbours, picking the best, building up a sorted part, splitting in half. These ideas appear again and again in other algorithms. And interviews and exams ask about them constantly.
The Words Used to Describe Sorting Algorithms
There are dozens of sorting algorithms. Programmers compare them using a few key properties.
1. Comparison-Based or Not
Most sorting algorithms work by comparing two values at a time: "is this one bigger than that one?" All six algorithms in this chapter are comparison-based.
A few special algorithms, like Counting Sort, never compare values directly. Instead they use the values themselves, for example as positions. They can be faster, but only work for certain kinds of data, such as small whole numbers.
2. In-Place or Extra Memory
An in-place algorithm rearranges the array itself, using only a tiny bit of extra memory. Others need a whole second array to work with, which matters when memory is limited.
3. Stable or Unstable
A stable algorithm keeps equal values in their original order. Imagine sorting students by marks, where Aarav and Diya both scored 85, and Aarav came first in the original list:
| Original order | Stable sort | Unstable sort (possible) |
|---|---|---|
| Aarav 85 | Kabir 72 | Kabir 72 |
| Kabir 72 | Aarav 85 | Diya 85 |
| Diya 85 | Diya 85 | Aarav 85 |
A stable sort guarantees Aarav stays ahead of Diya. That matters when you sort by one thing and then another, like by class and then by marks.
4. Adaptive or Not
An adaptive algorithm does less work when the data is already nearly sorted. A non-adaptive one does the same amount of work no matter what.
5. Simple or Efficient
This is the big one. Simple algorithms are easy to understand but take O(n²) time. Efficient ones take O(n log n). The difference becomes huge as data grows:
| Items (n) | O(n²) steps | O(n log n) steps |
|---|---|---|
| 10 | 100 | ~33 |
| 1,000 | 1,000,000 | ~9,966 |
| 1,000,000 | 1,000,000,000,000 | ~19,931,569 |
With a million items, an O(n²) sort could keep the computer busy for hours, while an O(n log n) sort finishes in about a second.
The Six Algorithms in This Chapter
| Algorithm | The idea | Best | Average | Worst | Extra memory | Stable |
|---|---|---|---|---|---|---|
| Bubble Sort | Swap neighbours that are out of order | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | Pick the smallest, put it in front | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion Sort | Insert each value into a sorted part | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge Sort | Split in half, sort, merge back | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | Split around a pivot value | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Heap Sort | Build a heap, move the biggest to the end | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
Don't try to memorise this table now. By the end of the chapter, every row will make sense, and each lesson has an animation so you can watch the algorithm work on the same array, [5, 1, 4, 2, 8].
How Do You Choose?
- Small or almost-sorted data: Insertion Sort is hard to beat.
- Need guaranteed speed, or a stable sort: Merge Sort.
- Fastest on average for large data: Quick Sort.
- Guaranteed speed without extra memory: Heap Sort.
- Writing to memory is expensive: Selection Sort, which makes at most
n − 1swaps. - Learning how sorting works: Bubble Sort, the simplest to follow.
In real projects, use the built-in sort. Python and JavaScript use Timsort, a clever mix of Merge Sort and Insertion Sort. Java uses a version of Quick Sort for numbers like int, and Timsort for objects. Under the hood, they are built from the same ideas you are about to learn.
In the next lesson, we will learn our first sorting algorithm: Bubble Sort.
Remember This
If you remember only one thing from this lesson, remember: Sorting arranges data in order so it can be searched, ranked and used easily. Algorithms are compared by speed, memory use, and whether they are stable.