Sorting algorithms
A sorting algorithm (English: Sorting algorithm) is an algorithm that arranges a series of data according to a particular sorting order; the sorted data can then be placed in an ordered array.
Sorting It refers to the process of rearranging a set of data (such as an array or list) into a specific order (ascending or descending).
The basis of sorting is usually somekeyof the data elements, such as the magnitude of numbers, the lexicographic order of strings, and so on.
Sorting is one of the most fundamental and core algorithmic problems in computer science. Whether organizing an address book, analyzing exam scores, or optimizing database queries, sorting algorithms are everywhere.
Understanding different sorting algorithms not only helps us solve practical problems but is also an excellent way to deeply understand the ideas of algorithm design and analysis.
Classification of sorting algorithms
Sorting algorithms can be classified along multiple dimensions; the most common classification is based on theirTime ComplexityandSpace complexity。
| Classification dimension | Category | Description | Typical algorithms |
|---|---|---|---|
| Time Complexity | O(n²) class | Simple and intuitive but less efficient, suitable for small-scale data. | Bubble sort, selection sort, insertion sort |
| O(n log n) class | More efficient, the preferred choice for large-scale data. | Quick sort, merge sort, heap sort | |
| Space complexity | in-place sort | Uses only a constant level of extra space during sorting. | Bubble, selection, insertion, shell, heap sort, quick sort |
| Non-in-place sorting | Requires extra space comparable to the data size during sorting. | Merge sort, counting sort, bucket sort, radix sort | |
| Stability | Stable sorting | The relative order of equal elements remains unchanged after sorting. | Bubble, insertion, merge, counting, bucket, radix sort |
| Unstable sorting | The relative order of equal elements may change after sorting. | Selection, shell, heap, quick sort |
Explanation of key concepts:
- Time Complexity: Measures the trend of an algorithm's execution time as the data size grows.
- Space complexity: Measures the amount of extra storage space required during an algorithm's execution.
- Stability: For elements with equal values, whether their relative order remains unchanged after sorting. This is very important in multi-key sorting.
The flowchart below shows how to make a preliminary choice among several classic algorithms based on different requirement scenarios:

Basic O(n²) sorting algorithms
These algorithms have simple ideas and are the starting point for understanding sorting logic.
Bubble Sort
Core idea: Repeatedly "traverse" the sequence to be sorted, comparing two adjacent elements at a time and swapping them if they are in the wrong order. Each traversal bubbles the largest (or smallest) element of the current unsorted portion to its correct position.
Algorithm steps:
- Compare adjacent elements. If the first is greater than the second (ascending order), swap them.
- Do the same for every pair of adjacent elements, from the first pair at the start to the last pair at the end. After this step, the last element will be the largest number.
- Repeat the above steps for all elements except the last one (because each round determines one final element).
- Continue repeating the above steps on fewer and fewer elements each time until no pair of numbers needs to be compared.
Code Implementation:
Example
def
bubble_sort
(
arr
)
:
"""
Bubble sort (ascending)
:param arr: the list to be sorted
"""
n
=
len
(
arr
)
The outer loop controls the number of rounds needed (n-1 rounds)
for
i
in
range
(
n -
1
)
:
The inner loop performs comparison and swapping of adjacent elements
After each round, the last i+1 elements are already in order, so the comparison range is 0 to n-1-i
for
j
in
range
(
0
,
n -
1
- i
)
:
if
arr
[
j
]
arr
[
j +
1
]
:
If the earlier element is greater than the later one
Swap the positions of the two elements
arr
[
j
]
,
arr
[
j +
1
]
=
arr
[
j +
1
]
,
arr
[
j
]
return
arr
Test Data
test_data
=
[
64
,
34
,
25
,
12
,
22
,
11
,
90
]
(
"Original array:"
,
test_data
)
sorted_data
=
bubble_sort
(
test_data.
copy
(
)
)
Use a copy to avoid modifying the original data
(
"After bubble sort:"
,
sorted_data
)
Output:
原始数组: [64, 34, 25, 12, 22, 11, 90]
冒泡排序后: [11, 12, 22, 25, 34, 64, 90]
Performance analysis:
- Time Complexity: Best case O(n) (when already sorted, achievable with optimization), worst and average cases O(n²).
- Space complexity: O(1), an in-place sort.
- Stability: Stable.
Selection Sort
Core idea: Find the smallest (or largest) element in the unsorted sequence, place it at the start of the sorted sequence, then continue to find the smallest (largest) element from the remaining unsorted elements and place it at the end of the sorted sequence. Repeat until all elements are sorted.
Algorithm steps:
- Initial state: the entire sequence is the unsorted region.
- In the i-th round (i starting from 0), the current unsorted region is
arr[i...n-1]. Select the record with the smallest key from this regionarr[min_index]。 - data to the child component via
arr[min_index]and swap it with the first record of the unsorted regionarr[i]. In this way,arr[0...i]forms the sorted region. - After n-1 rounds, the array is sorted.
Code Implementation:
Example
def
selection_sort
(
arr
)
:
"""
Selection sort (ascending)
:param arr: the list to be sorted
"""
n
=
len
(
arr
)
for
i
in
range
(
n
)
:
Assume the element at current index i is the smallest
min_index
=
i
Search for a smaller element in the range i+1 to n-1
for
j
in
range
(
i +
1
,
n
)
:
if
arr
[
j
]
<
arr
[
min_index
]:
min_index
=
j
Update the index of the smallest element
Swap the found smallest element with the element at position i
arr
[
i
]
,
arr
[
min_index
]
=
arr
[
min_index
]
,
arr
[
i
]
return
arr
Testing
test_data
=
[
64
,
25
,
12
,
22
,
11
]
(
"Original array:"
,
test_data
)
(
"After selection sort:"
,
selection_sort
(
test_data.
copy
(
)
)
)
Output:
原始数组: [64, 25, 12, 22, 11]
选择排序后: [11, 12, 22, 25, 64]
Performance analysis:
- Time Complexity: Always O(n²), because a full set of comparisons is needed regardless of whether the data is sorted.
- Space complexity: O(1), in-place sorting.
- Stability:Unstable. For example, the sequence
[5, 8, 5, 2, 9], the first round would swap the first element with the last,5and2destroying the original order of the two5equal elements.
Insertion Sort
Core idea: By building a sorted sequence, for unsorted data, scan from back to front in the sorted sequence to find the appropriate position and insert. This is like how we sort playing cards.
Algorithm steps:
- Treat the first element as the sorted sequence.
- Take the next element and scan from back to front in the already sorted element sequence.
- If that element (sorted) is greater than the new element, move it to the next position.
- Repeat step 3 until a position is found where the sorted element is less than or equal to the new element.
- Insert the new element after that position.
- Repeat steps 2-5 until all elements are processed.
Code Implementation:
Example
def
insertion_sort
(
arr
)
:
"""
Insertion sort (ascending)
:param arr: the list to be sorted
"""
n
=
len
(
arr
)
Start from the second element (index 1), because the first element is sorted by default
for
i
in
range
(
1
,
n
)
:
key
=
arr
[
i
]
the current element to insert
j
=
i -
1
the index of the last element of the sorted sequence
Scan the sorted sequence from back to front to find the insertion position for key
Meanwhile, move elements greater than key one position back
while
j
=
0
and
key
<
arr
[
j
]:
arr
[
j +
1
]
=
arr
[
j
]
j -
=
1
Insert key into the found correct position
arr
[
j +
1
]
=
key
return
arr
Testing
test_data
=
[
12
,
11
,
13
,
5
,
6
]
(
"Original array:"
,
test_data
)
(
"After insertion sort:"
,
insertion_sort
(
test_data.
copy
(
)
)
)
Output:
原始数组: [12, 11, 13, 5, 6]
插入排序后: [5, 6, 11, 12, 13]
Performance analysis:
- Time Complexity: Best case O(n) (already sorted), worst and average cases O(n²).
- Space complexity: O(1), in-place sorting.
- Stability: Stable.
- Feature: For small-scale or nearly sorted data, insertion sort is very efficient. It is the algorithm that advanced sorting algorithms (such as Timsort) switch to for small-scale data.
Efficient O(n log n) sorting algorithms
When the data size grows, O(n²) algorithms become very slow. The more efficient algorithms below are the mainstay of engineering practice.
Quick Sort
Core idea:Divide and conquer. Choose a pivot element and, through a single pass of sorting, partition the records into two independent parts, where the keys of one part are all smaller than those of the other; then continue sorting the two parts separately to make the whole sequence ordered.
Algorithm steps:
- Choose a pivot: Pick an element from the sequence, called the "pivot".
- Partition operation: Rearrange the sequence so that all elements smaller than the pivot are placed before it and all larger elements are placed after it (equal numbers may go to either side). After the partition exits, the pivot is in the middle of the sequence. This is called a partition operation.
- Recursive Sorting: Recursively sort the sub-sequence of elements smaller than the pivot and the sub-sequence of elements larger than the pivot.
Code Implementation:
Example
def
quick_sort
(
arr
)
:
"""
Quick sort (ascending) - main function
"""
def
_quick_sort
(
arr
,
low
,
high
)
:
if
low
<
high:
pi is the partition index; arr[pi] is now in the correct position
pi
=
partition
(
arr
,
low
,
high
)
Recursively sort the sub-arrays before and after the partition
_quick_sort
(
arr
,
low
,
pi -
1
)
_quick_sort
(
arr
,
pi +
1
,
high
)
def
partition
(
arr
,
low
,
high
)
:
"""
Partition function, choosing the last element as the pivot
:return: the final correct position index of the pivot element
"""
pivot
=
arr
[
high
]
Choose a pivot
i
=
low -
1
Points to the end of the sub-array of elements smaller than the pivot
for
j
in
range
(
low
,
high
)
:
If the current element is less than or equal to the pivot
if
arr
[
j
]
<=
pivot:
i +
=
1
arr
[
i
]
,
arr
[
j
]
=
arr
[
j
]
,
arr
[
i
]
Swap
Place the pivot element in the correct position (i+1)
arr
[
i +
1
]
,
arr
[
high
]
=
arr
[
high
]
,
arr
[
i +
1
]
return
i +
1
_quick_sort
(
arr
,
0
,
len
(
arr
)
1
)
return
arr
Testing
test_data
=
[
10
,
80
,
30
,
90
,
40
,
50
,
70
]
(
"Original array:"
,
test_data
)
(
"After quick sort:"
,
quick_sort
(
test_data.
copy
(
)
)
)
Output:
原始数组: [10, 80, 30, 90, 40, 50, 70]
快速排序后: [10, 30, 40, 50, 70, 80, 90]
Performance analysis:
- Time Complexity: Average case O(n log n), worst case O(n²) (when the array is already sorted or reverse-sorted and the pivot is chosen poorly). The worst case can be largely avoided by randomly selecting the pivot or using the "median-of-three" method.
- Space complexity: Average O(log n) (recursive call stack), worst O(n).
- Stability:Unstable。
Merge Sort
Core idea:Divide and conquerA typical application of merge sort. Merge the already sorted sub-sequences to obtain a completely sorted sequence. That is, first make each sub-sequence sorted, then make the segments between sub-sequences sorted.
Algorithm steps:
- Decomposition: Split the current interval in two, i.e., find the split point
mid = (low + high)/2。 - Solve: Recursively, for the two sub-intervals
arr[low...mid]andarr[mid+1...high]perform merge sort. The recursion terminates when a sub-interval has length 1 (a single element is considered naturally sorted). - Collapse: Merge two sorted sub-intervals into one sorted interval.
Code Implementation:
Example
def
merge_sort
(
arr
)
:
"""
Merge sort (ascending) - main function
"""
if
len
(
arr
)
1
:
mid
=
len
(
arr
)
//
2
Find the midpoint and split the array
left_half
=
arr
[
:mid
]
right_half
=
arr
[
mid:
]
Recursively sort the left and right halves
merge_sort
(
left_half
)
merge_sort
(
right_half
)
Merge the two sorted sub-arrays
i
=
j
=
k
=
0
Compare elements of the left and right sub-arrays, placing the smaller one into the original array
while
i
<
len
(
left_half
)
and
j
<
len
(
right_half
):
if
left_half
[
i
]
<
right_half
[
j
]:
arr
[
k
]
=
left_half
[
i
]
i +
=
1
else
:
arr
[
k
]
=
right_half
[
j
]
j +
=
1
k +
=
1
Check whether there are remaining elements (in the left or right half)
while
i
<
len
(
left_half
):
arr
[
k
]
=
left_half
[
i
]
i +
=
1
k +
=
1
while
j
<
len
(
right_half
):
arr
[
k
]
=
right_half
[
j
]
j +
=
1
k +
=
1
return
arr
Testing
test_data
=
[
38
,
27
,
43
,
3
,
9
,
82
,
10
]
(
"Original array:"
,
test_data
)
(
"After merge sort:"
,
merge_sort
(
test_data.
copy
(
)
)
)
Output:
原始数组: [38, 27, 43, 3, 9, 82, 10]
归并排序后: [3, 9, 10, 27, 38, 43, 82]
Performance analysis:
- Time Complexity: Best, worst, and average cases are all O(n log n). Performance is very stable.
- Space complexity: O(n), requiring extra space equal to the original array for merging.
- Stability: Stable.
Heap sort
Core idea: UsesHeapA sorting algorithm designed for this data structure. A heap is a structure approximating a complete binary tree that also satisfies the heap property: the value of a parent node is always greater than or equal to (max heap) or less than or equal to (min heap) the value of any child node.
Algorithm steps:
- Build a max heap: Construct the sequence to be sorted into a max heap. At this point, the maximum value of the whole sequence is the root node at the top of the heap.
- Swap the heap top with the last element: Swap the heap top element (the maximum) with the last element, so the last element becomes the maximum.
- Adjust the heap structure: Rebuild the remaining
n-1elements into a max heap, which yields the second-largest value. Swap it with the new last position (n-1). - Repeat steps 2 and 3 until the heap size is 1, at which point sorting is complete.
Code Implementation:
Example
def
heap_sort
(
arr
)
:
"""
Heap sort (ascending) - using a max heap
"""
n
=
len
(
arr
)
Step 1: Build a max heap. Adjust upward starting from the last non-leaf node
The index of the last non-leaf node = n//2 - 1
for
i
in
range
(
n //
2
1
,
1
,
1
)
:
heapify
(
arr
,
n
,
i
)
Steps 2 & 3: Extract the heap-top element (the maximum) one by one and adjust the heap
for
i
in
range
(
n -
1
,
0
,
1
)
:
Swap the current heap top (the maximum) with the last element
arr
[
i
]
,
arr
[
0
]
=
arr
[
0
]
,
arr
[
i
]
Adjust the remaining elements to make them a max heap again, reducing the heap size to i
heapify
(
arr
,
i
,
0
)
return
arr
def
heapify
(
arr
,
n
,
i
)
:
"""
Adjust the subtree rooted at i to make it a max heap
:param arr: the heap array
:param n: the current size of the heap
:param i: the index of the current root node
"""
largest
=
i
Initialize the maximum as the root
left
=
2
- i +
1
left child index
right
=
2
- i +
2
right child index
If the left child exists and is greater than the root
if
left
<
n
and
arr
[
left
]
arr
[
largest
]:
largest
=
left
If the right child exists and is greater than the current maximum
if
right
<
n
and
arr
[
right
]
arr
[
largest
]:
largest
=
right
If the maximum is not the root, swap and recursively adjust the broken sub-heap
if
largest
!=
i:
arr
[
i
]
,
arr
[
largest
]
=
arr
[
largest
]
,
arr
[
i
]
heapify
(
arr
,
n
,
largest
)
Testing
test_data
=
[
4
,
10
,
3
,
5
,
1
]
(
"Original array:"
,
test_data
)
(
"After heap sort:"
,
heap_sort
(
test_data.
copy
(
)
)
)
Output:
原始数组: [4, 10, 3, 5, 1]
堆排序后: [1, 3, 4, 5, 10]
Performance analysis:
- Time Complexity: Best, worst, and average cases are all O(n log n).
- Space complexity: O(1), in-place sorting.
- Stability:Unstable。
Summary of algorithm performance comparison
To compare the characteristics of the above algorithms more intuitively, we summarize them in the following table:
| Algorithm | Average time complexity | Worst-case time complexity | Space complexity | Stability | Main Features |
|---|---|---|---|---|---|
| Bubble Sort | O(n²) | O(n²) | O(1) | Stable | Simple, inefficient, suitable for teaching. |
| Selection Sort | O(n²) | O(n²) | O(1) | Unstable | Few swaps, but a fixed large number of comparisons. |
| Insertion Sort | O(n²) | O(n²) | O(1) | Stable | Efficient for small-scale or nearly sorted data. |
| Quick Sort | O(n log n) | O(n²) | O(log n) | Unstable | Best average performance, the most widely used sorting algorithm. |
| Merge Sort | O(n log n) | O(n log n) | O(n) | Stable | Stable performance, but requires extra space. Often used for external sorting. |
| Heap sort | O(n log n) | O(n log n) | O(1) | Unstable | In-place sorting, and the worst case is also O(n log n). |
Practical Exercise
After theoretical study, hands-on practice is the best way to consolidate knowledge.
Exercise 1: Algorithm selection and implementation
Given the following scenarios, which sorting algorithm would you choose? Briefly explain your reasons.
- Sort an array containing 10 numbers.
- Sort a linked list containing one million student objects by student ID, requiring stability.
- Sort a large array in an embedded system with limited memory.
- Need to obtain the top K largest elements from a data stream in real time.
Reference answer ideas:
- Insertion Sort. The data size is small; insertion sort is simple, friendly to nearly sorted data, and has a small constant factor.
- Merge Sort. The data size is large, stable sorting is required, and the linked list structure allows merge sort's merge operation to complete in O(1) space (just modify pointers).
- Heap sort. Memory is limited, in-place sorting is needed, and heap sort guarantees O(n log n) performance even in the worst case.
- Maintain a min-heap of size K. Traverse the data stream and use the heap to maintain the current largest K elements. This is not a complete sort, but it leverages the heap's properties.
Exercise 2: Code debugging and optimization
The bubble sort below has a small bug and one place that can be optimized; find and fix them.
Example
def
bubble_sort_buggy
(
arr
)
:
n
=
len
(
arr
)
for
i
in
range
(
n
)
:
for
j
in
range
(
n -
1
)
:
if
arr
[
j
]
arr
[
j
]
:
arr
[
j
]
,
arr
[
j+
1
]
=
arr
[
j+
1
]
,
arr
[
j
]
return
arr
Tip:
- The comparison condition
arr[j] > arr[j]is always false. - The boundary of the inner loop can be optimized because after each round, the elements at the end are already sorted.
Exercise 3: Hands-on implementation
Try implementing from scratch yourselfQuick Sort, and think about:
- If the pivot
pivotis always chosen as the first element, what happens when sorting an already sorted array? - How to modify the
partitionfunction to turn it into a "three-way quick sort" that handles arrays with many duplicate elements more efficiently?