Retranslate the complete English edition from Simplified Chinese (#2010)

* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
This commit is contained in:
Yudong Jin
2026-10-31 03:35:51 +08:00
committed by GitHub
parent ef46e2ed95
commit 14c314c08c
1502 changed files with 29459 additions and 23517 deletions

View File

@@ -1,11 +1,11 @@
# Bubble Sort
# Bubble sort
<u>Bubble sort</u> sorts an array by continuously comparing and swapping adjacent elements. This process resembles bubbles rising from the bottom to the top, hence the name bubble sort.
<u>Bubble sort</u> sorts by repeatedly comparing and swapping adjacent elements. The process resembles bubbles rising from the bottom to the top, which gives the algorithm its name.
As shown in the figure below, the bubbling process can be simulated using element swaps: starting from the leftmost end of the array and traversing to the right, compare each pair of adjacent elements, and if "left element > right element", swap them. After the traversal is complete, the largest element is moved to the rightmost end of the array.
As shown below, we can simulate bubbling through swaps. Scan from the left end of the array to the right, comparing each pair of adjacent elements. If the left element is greater than the right, swap them. After the scan, the largest element has moved to the far right.
=== "<1>"
![Simulating bubble sort using element swaps](bubble_sort.assets/bubble_operation_step1.png)
![Simulating bubbling through element swaps](bubble_sort.assets/bubble_operation_step1.png)
=== "<2>"
![bubble_operation_step2](bubble_sort.assets/bubble_operation_step2.png)
@@ -25,35 +25,35 @@ As shown in the figure below, the bubbling process can be simulated using elemen
=== "<7>"
![bubble_operation_step7](bubble_sort.assets/bubble_operation_step7.png)
## Algorithm Flow
## Algorithm steps
Assume the array has length $n$. The steps of bubble sort are shown in the figure below.
For an array of length $n$, bubble sort proceeds as shown below.
1. First, perform "bubbling" on $n$ elements, **swapping the largest element of the array to its correct position**.
2. Next, perform "bubbling" on the remaining $n - 1$ elements, **swapping the second largest element to its correct position**.
3. And so on. After $n - 1$ rounds of "bubbling", **the largest $n - 1$ elements have all been swapped to their correct positions**.
4. The only remaining element must be the smallest element, requiring no sorting, so the array sorting is complete.
1. First, perform a bubbling pass over all $n$ elements, **moving the largest element to its correct position**.
2. Next, perform a pass over the remaining $n - 1$ elements, **moving the second-largest element to its correct position**.
3. Continue in this way. After $n - 1$ passes, **the largest $n - 1$ elements are all in their correct positions**.
4. The one remaining element must be the smallest and needs no further sorting. The array is now sorted.
![Bubble sort flow](bubble_sort.assets/bubble_sort_overview.png)
![The bubble sort process](bubble_sort.assets/bubble_sort_overview.png)
Example code is as follows:
An implementation follows:
```src
[file]{bubble_sort}-[class]{}-[func]{bubble_sort}
```
## Efficiency Optimization
## Improving efficiency
We can observe that if no swaps occur during a round of "bubbling", the array is already sorted and the algorithm can return immediately. Therefore, we can add a flag `flag` to detect this situation and terminate as soon as it occurs.
If a bubbling pass performs no swaps, the array is already sorted and we can return immediately. We can therefore add a variable `flag` to detect this situation and stop as soon as it occurs.
After this optimization, the worst-case and average-case time complexities of bubble sort remain $O(n^2)$; however, when the input array is already sorted, the best-case time complexity becomes $O(n)$.
With this optimization, the worst-case and average time complexities remain $O(n^2)$. However, a fully sorted input achieves the best-case time complexity of $O(n)$.
```src
[file]{bubble_sort}-[class]{}-[func]{bubble_sort_with_flag}
```
## Algorithm Characteristics
## Algorithm properties
- **Time complexity is $O(n^2)$; adaptive**: In successive rounds of "bubbling", the traversed portion of the array has lengths $n - 1$, $n - 2$, $\dots$, $2$, $1$, for a total of $(n - 1) n / 2$. After introducing the `flag` optimization, the best-case time complexity can reach $O(n)$.
- **Space complexity of $O(1)$, in-place sorting**: Pointers $i$ and $j$ use a constant amount of extra space.
- **Stable sorting**: Equal elements are not swapped during "bubbling".
- **Time complexity: $O(n^2)$; adaptive**. Successive passes traverse $n - 1$, $n - 2$, $\dots$, $2$, and $1$ positions, totaling $(n - 1) n / 2$. With the `flag` optimization, the best-case time complexity is $O(n)$.
- **Space complexity: $O(1)$; in-place**. Pointers $i$ and $j$ use constant extra space.
- **Stable**. Equal elements are not swapped during a bubbling pass.

View File

@@ -1,18 +1,18 @@
# Bucket Sort
# Bucket sort
The sorting algorithms discussed earlier are all comparison-based sorting algorithms, which sort by comparing the relative order of elements. The worst-case time complexity of such algorithms has a lower bound of $\Omega(n \log n)$. Next, we will explore several non-comparison sorting algorithms, whose time complexity can be linear.
The sorting algorithms discussed so far are “comparison-based”: they sort by comparing elements. Their worst-case time complexity has a lower bound of $\Omega(n \log n)$. We now turn to several “non-comparison” sorting algorithms, which can achieve linear time complexity.
<u>Bucket sort</u> is a typical application of the divide-and-conquer strategy. It works by creating a sequence of ordered buckets, each corresponding to a data range, and distributing the data evenly among them. The elements within each bucket are then sorted separately. Finally, all buckets are merged in order.
<u>Bucket sort</u> is a classic application of divide and conquer. It creates ordered buckets, each corresponding to a range of values, and distributes the data evenly among them. It then sorts each bucket separately and combines the results in bucket order.
## Algorithm Flow
## Algorithm steps
Consider an array of length $n$, whose elements are floating-point numbers in the range $[0, 1)$. The flow of bucket sort is shown in the figure below.
Consider an array of length $n$ containing floating-point values in $[0, 1)$. Bucket sort proceeds as shown below.
1. Initialize $k$ buckets and distribute the $n$ elements into the $k$ buckets.
2. Sort each bucket separately (here we use the built-in sorting function of the programming language).
3. Merge the results in order from smallest to largest bucket.
1. Initialize $k$ buckets and distribute the $n$ elements among the $k$ buckets.
2. Sort each bucket separately, using the programming language's built-in sorting function here.
3. Combine the results in ascending bucket order.
![Bucket sort algorithm flow](bucket_sort.assets/bucket_sort_overview.png)
![The bucket sort process](bucket_sort.assets/bucket_sort_overview.png)
The code is as follows:
@@ -20,26 +20,26 @@ The code is as follows:
[file]{bucket_sort}-[class]{}-[func]{bucket_sort}
```
## Algorithm Characteristics
## Algorithm properties
Bucket sort is suitable for processing very large datasets. For example, suppose the input contains 1 million elements, and limited memory prevents the system from loading all of them at once. In that case, the data can be divided into 1000 buckets, each bucket can be sorted separately, and the results can then be merged.
Bucket sort is useful for very large datasets. For example, suppose the input contains one million elements and memory limitations prevent loading all of them at once. We can divide them into 1,000 buckets, sort the buckets separately, and combine the results.
- **Time complexity is $O(n + k)$**: Assuming the elements are evenly distributed across the buckets, each bucket contains $\frac{n}{k}$ elements. If sorting a single bucket takes $O(\frac{n}{k} \log\frac{n}{k})$ time, then sorting all buckets takes $O(n \log\frac{n}{k})$ time. **When the number of buckets $k$ is relatively large, the time complexity approaches $O(n)$**. Merging the results requires traversing all buckets and elements, which takes $O(n + k)$ time. In the worst case, all data is placed into a single bucket, and sorting that bucket takes $O(n^2)$ time.
- **Space complexity is $O(n + k)$, and bucket sort is not in-place**: It requires extra space for $k$ buckets and a total of $n$ elements.
- Whether bucket sort is stable depends on whether the algorithm for sorting elements within buckets is stable.
- **Time complexity: $O(n + k)$**. If the elements are evenly distributed, each bucket contains $\frac{n}{k}$ elements. If sorting one bucket takes $O(\frac{n}{k} \log\frac{n}{k})$ time, sorting all buckets takes $O(n \log\frac{n}{k})$. **When the number of buckets $k$ is relatively large, this approaches $O(n)$**. Combining the results visits all buckets and elements, taking $O(n + k)$ time. In the worst case, all data falls into one bucket, and sorting it takes $O(n^2)$ time.
- **Space complexity: $O(n + k)$; not in-place**. Extra space is needed for $k$ buckets and a total of $n$ elements.
- Whether bucket sort is stable depends on whether the algorithm used to sort within each bucket is stable.
## How to Achieve Even Distribution
## Distributing elements evenly
In theory, bucket sort can achieve $O(n)$ time complexity. **The key is to distribute the elements evenly across the buckets**, because real-world data is often not uniformly distributed. For example, suppose we want to divide all products on Taobao evenly into 10 buckets by price range, but the price distribution is uneven: there are many products priced below 100 yuan and very few priced above 1000 yuan. If the price range is divided evenly into 10 intervals, the numbers of products in the buckets will differ greatly.
Bucket sort can theoretically achieve $O(n)$ time. **The key is distributing elements evenly among the buckets**, since real data is often unevenly distributed. Suppose we want to divide all products on Taobao evenly into 10 buckets by price. There are many products below 100 yuan but few above 1,000 yuan. Splitting the price range into 10 equal intervals would leave very different numbers of products in the buckets.
To achieve a more even distribution, we can first choose a rough boundary and partition the data into 3 buckets. **After that, buckets containing more products can be further divided into 3 buckets until the numbers of elements in all buckets are roughly equal**.
To obtain an even distribution, we can first choose rough boundaries and divide the data into 3 buckets. **Then split the more crowded buckets into 3 smaller buckets, repeating until all buckets contain roughly equal numbers of elements**.
As shown in the figure below, this method essentially builds a recursion tree whose goal is to make the leaf nodes as balanced as possible. Of course, the data does not have to be split into 3 buckets in every round; the specific partitioning strategy can be chosen flexibly based on the characteristics of the data.
As shown below, this effectively creates a recursion tree whose leaf values should be as balanced as possible. We need not use 3 buckets at every step; the subdivision can be chosen to suit the data.
![Recursively dividing buckets](bucket_sort.assets/scatter_in_buckets_recursively.png)
![Recursively subdividing buckets](bucket_sort.assets/scatter_in_buckets_recursively.png)
If we know the probability distribution of product prices in advance, **we can set the price boundaries for each bucket according to that distribution**. Notably, the data distribution does not need to be measured exactly; it can also be approximated with a probability model chosen to fit the characteristics of the data.
If we know the probability distribution of product prices in advance, **we can choose bucket boundaries according to that distribution**. We do not necessarily need to measure the distribution explicitly; we can approximate it with a probability model suited to the data.
As shown in the figure below, we assume that product prices follow a normal distribution, which allows us to reasonably set price intervals to evenly distribute products to each bucket.
In the figure below, we assume prices follow a normal distribution. This lets us choose suitable price intervals and distribute products evenly among the buckets.
![Dividing buckets based on probability distribution](bucket_sort.assets/scatter_in_buckets_distribution.png)
![Defining buckets from a probability distribution](bucket_sort.assets/scatter_in_buckets_distribution.png)

View File

@@ -1,16 +1,16 @@
# Counting Sort
# Counting sort
<u>Counting sort</u> sorts by counting the occurrences of elements and is typically applied to integer arrays.
<u>Counting sort</u> sorts by counting how often each element occurs. It is typically used for integer arrays.
## Simple Implementation
## A simple implementation
Let's start with a simple example. Given an array `nums` of length $n$, where the elements are all "non-negative integers", the overall flow of counting sort is shown in the figure below.
Start with a simple example: an array `nums` of length $n$ containing nonnegative integers. The overall process is shown below.
1. Traverse the array to find the largest number, denoted as $m$, and then create an auxiliary array `counter` of length $m + 1$.
2. **Use `counter` to count how many times each number appears in `nums`**, where `counter[num]` stores the number of occurrences of `num`. This is simple: traverse `nums` (denote the current number by `num`) and increment `counter[num]` by $1$ each time.
3. **Because the indices of `counter` are naturally ordered, the numbers are effectively already sorted**. Next, traverse `counter` and write the numbers back into `nums` in ascending order according to their occurrence counts.
1. Traverse the array to find its maximum value, denoted by $m$, then create an auxiliary array `counter` of length $m + 1$.
2. **Use `counter` to count occurrences of each number in `nums`**. Here, `counter[num]` is the number of occurrences of `num`. Simply traverse `nums` and increment `counter[num]` by $1$ for each current value `num`.
3. **Because the indices of `counter` are inherently ordered, the numbers are effectively already sorted**. Traverse `counter` and write each number into `nums` in ascending order, repeating it according to its count.
![Counting sort flow](counting_sort.assets/counting_sort_overview.png)
![The counting sort process](counting_sort.assets/counting_sort_overview.png)
The code is as follows:
@@ -18,29 +18,29 @@ The code is as follows:
[file]{counting_sort}-[class]{}-[func]{counting_sort_naive}
```
!!! note "Connection between counting sort and bucket sort"
!!! note "How counting sort relates to bucket sort"
From the perspective of bucket sort, each index of the counting array `counter` can be viewed as a bucket, and the counting process can be seen as distributing elements into their corresponding buckets. Essentially, counting sort is a special case of bucket sort for integer data.
From a bucket-sort perspective, each index of `counter` is a bucket, and counting occurrences is equivalent to distributing elements into their corresponding buckets. Counting sort is essentially a special case of bucket sort for integer data.
## Complete Implementation
## A complete implementation
Observant readers may have noticed that **if the input consists of objects, step `3.` above no longer works**. Suppose the input consists of product objects and we want to sort them by price (a member variable of the class); the above algorithm can only produce the sorted order of the prices themselves.
You may have noticed that **step `3.` above fails when the input consists of objects**. Suppose the inputs are product objects and we want to sort them by price, a member variable of the class. The algorithm above can produce only the sorted prices.
So how can we obtain the sorted order of the original data? We first compute the prefix sums of `counter`. As the name suggests, the prefix sum at index `i`, `prefix[i]`, equals the sum of the elements from index `0` through `i`:
How can we obtain the sorted original data? First, calculate the “prefix sums” of `counter`. The prefix sum `prefix[i]` is the sum of the array entries up to index `i`:
$$
\text{prefix}[i] = \sum_{j=0}^i \text{counter[j]}
$$
**The prefix sum has a clear interpretation: `prefix[num] - 1` gives the index of the last occurrence of element `num` in the result array `res`**. This information is crucial because it tells us where each element should be placed in the result array. Next, we traverse the original array `nums` in reverse, and for each element `num`, perform the following two steps.
**The prefix sum has a precise meaning: `prefix[num] - 1` is the index of the last occurrence of `num` in the result array `res`**. This tells us where each element belongs. Next, traverse the original array `nums` in reverse and perform two steps for each element `num`.
1. Place `num` at index `prefix[num] - 1` of the array `res`.
2. Decrease the prefix sum `prefix[num]` by $1$ to get the index for the next placement of `num`.
1. Place `num` at index `prefix[num] - 1` in `res`.
2. Decrease `prefix[num]` by $1$ to obtain the index for placing the next occurrence of `num`.
After the traversal is complete, the array `res` contains the sorted result, and finally `res` is used to overwrite the original array `nums`. The complete counting sort flow is shown in the figure below.
After the traversal, `res` contains the sorted result. Finally, copy `res` over the original array `nums`. The figure below shows the complete process.
=== "<1>"
![Counting sort steps](counting_sort.assets/counting_sort_step1.png)
![Steps of counting sort](counting_sort.assets/counting_sort_step1.png)
=== "<2>"
![counting_sort_step2](counting_sort.assets/counting_sort_step2.png)
@@ -63,22 +63,22 @@ After the traversal is complete, the array `res` contains the sorted result, and
=== "<8>"
![counting_sort_step8](counting_sort.assets/counting_sort_step8.png)
The counting sort implementation is shown below:
The implementation is as follows:
```src
[file]{counting_sort}-[class]{}-[func]{counting_sort}
```
## Algorithm Characteristics
## Algorithm properties
- **Time complexity is $O(n + m)$, and counting sort is non-adaptive**: Traversing `nums` and `counter` both takes linear time. In general, when $n \gg m$, the time complexity approaches $O(n)$.
- **Space complexity of $O(n + m)$, non-in-place sorting**: Uses arrays `res` and `counter` of lengths $n$ and $m$ respectively.
- **Stable sorting**: Since elements are filled into `res` in a "right-to-left" order, traversing `nums` in reverse can avoid changing the relative positions of equal elements, thereby achieving stable sorting. In fact, traversing `nums` in forward order can also yield correct sorting results, but the result would be unstable.
- **Time complexity: $O(n + m)$; not adaptive**. Traversing `nums` and `counter` each takes linear time. Usually $n \gg m$, so the complexity approaches $O(n)$.
- **Space complexity: $O(n + m)$; not in-place**. The algorithm uses arrays `res` and `counter` of lengths $n$ and $m$, respectively.
- **Stable**. Since elements are placed into `res` from right to left, traversing `nums` in reverse preserves the relative order of equal elements. A forward traversal also produces a correctly sorted result, but it is not stable.
## Limitations
At this point, you might think counting sort is quite ingenious because it achieves efficient sorting simply by counting occurrences. However, the prerequisites for using counting sort are fairly restrictive.
Counting sort may seem ingenious: it sorts efficiently simply by counting occurrences. However, its prerequisites are relatively restrictive.
**Counting sort is only applicable to non-negative integers**. To apply it to other types of data, you must ensure that they can be converted to non-negative integers without changing the relative ordering of the elements. For example, for an integer array containing negative numbers, you can first add a constant to every number to shift them into the non-negative range, and then shift them back after sorting.
**Counting sort applies only to nonnegative integers**. For other data types, the values must be convertible to nonnegative integers without changing their relative order. For example, if an integer array contains negative numbers, add a constant to every element to make them all positive, sort, and then reverse the transformation.
**Counting sort is well suited to cases with many elements but a small value range**. For example, in the above scenario, $m$ cannot be too large; otherwise, it consumes too much space. And when $n \ll m$, counting sort takes $O(m)$ time, which may be slower than sorting algorithms with $O(n \log n)$ time complexity.
**Counting sort suits large datasets with a relatively small value range**. In the example above, $m$ must not be too large, or the algorithm will consume excessive space. When $n \ll m$, counting sort takes $O(m)$ time and may be slower than an $O(n \log n)$ sorting algorithm.

View File

@@ -1,94 +1,94 @@
# Exercises
## Concept Review
## Check your understanding
### The First Few Rounds of Selection Sort and Bubble Sort
### The first passes of selection sort and bubble sort
Given the array `[4, 2, 5, 1, 3]`, sort it in ascending order in both parts below.
Given the array `[4, 2, 5, 1, 3]`, sort in ascending order throughout this exercise.
<!-- numbered-subquestions -->
1. Simulate the first two rounds of selection sort. Write the array after each round and identify which positions are now fixed.
2. Simulate the first round of bubble sort. Write the resulting array and the number of swaps, and identify which position is now fixed.
1. Simulate the first two passes of selection sort. Write the array after each pass and identify the positions whose final values are now fixed.
2. Simulate the first pass of bubble sort. Write the array and the number of swaps, and identify the position whose final value is now fixed.
??? success "Answer"
??? success "Reference answer"
1. The first two rounds are:
1. The first two passes are:
| Round | Array | Explanation |
| Pass | Array | Explanation |
| --- | --- | --- |
| 1 | `[1, 2, 5, 4, 3]` | The smallest element, 1, is swapped with the first element |
| 1 | `[1, 2, 5, 4, 3]` | Swap the minimum element, 1, with the first element |
| 2 | `[1, 2, 5, 4, 3]` | The value 2 is already at index 1, so no swap is needed |
The first two positions are now fixed. Later rounds need to find the smallest element only within `[5, 4, 3]`.
The first two positions are now fixed. Subsequent passes need only continue selecting the minimum from `[5, 4, 3]`.
2. Compare adjacent elements in order: swap 4 and 2; do not swap 4 and 5; swap 5 and 1; then swap 5 and 3.
The result is `[2, 4, 1, 3, 5]`, after 3 swaps. The largest element, 5, has moved to the end of the array, so the last position is now fixed.
2. Compare adjacent elements in order: swap 4 and 2, leave 4 and 5 unchanged, swap 5 and 1, then swap 5 and 3.
The result is `[2, 4, 1, 3, 5]`, with three swaps. The maximum element, 5, has moved to the end, fixing the last position.
### Can Equal Elements Change Their Relative Order?
### Does the order of equal elements change?
In the array $[2_a, 2_b, 1]$, $2_a$ and $2_b$ have equal values, but their subscripts mark their original order.
In the array $[2_a, 2_b, 1]$, $2_a$ and $2_b$ have equal values; the subscripts mark their original order.
<!-- numbered-subquestions -->
1. Write the array after the first round of selection sort. Has the relative order of $2_a$ and $2_b$ changed?
2. Write the array after the first round of bubble sort. Has the relative order of $2_a$ and $2_b$ changed?
3. Based on the first two questions, explain how the two sorting algorithms differ in preserving the original order of equal elements.
1. Write the array after the first pass of selection sort. Has the relative order of $2_a$ and $2_b$ changed?
2. Write the array after the first pass of bubble sort. Has the relative order of $2_a$ and $2_b$ changed?
3. Based on your answers, explain how the two algorithms differ in preserving the original order of equal elements.
??? success "Answer"
??? success "Reference answer"
1. In its first round, selection sort selects the smallest element, 1, and swaps it with the first element, $2_a$, producing
$[1, 2_b, 2_a]$. The relative order has changed because $2_a$ has moved behind $2_b$.
1. The first pass of selection sort selects the minimum element, 1, and swaps it with the first element, $2_a$, producing
$[1, 2_b, 2_a]$. The swap moves $2_a$ after $2_b$, changing their relative order.
2. Bubble sort first compares $2_a$ and $2_b$. Because they are equal, it does not swap them. It then compares $2_b$ and 1 and swaps them,
producing $[2_a, 1, 2_b]$ after the first round. $2_a$ is still before $2_b$, so their relative order has not changed.
2. Bubble sort first compares $2_a$ with $2_b$ and does not swap them because they are equal. It then compares and swaps $2_b$ and 1.
After the first pass, the array is $[2_a, 1, 2_b]$. Since $2_a$ still precedes $2_b$, their relative order is unchanged.
3. In this example, selection sort changes the original order of equal elements. Bubble sort swaps adjacent elements only when the left element is greater than the right one.
Equal elements are not swapped, so their original relative order is preserved.
3. In this example, selection sort changes the original order of equal elements. Bubble sort swaps adjacent elements only when the left element
is greater than the right one. Equal elements are never swapped with each other, so their original order is preserved.
### Compare Counting Sort and Radix Sort
### Comparing counting sort and radix sort
A school needs to sort many student ID numbers, each exactly 8 digits long. Answer the following questions:
A school needs to sort many student IDs, each exactly eight digits long. Answer the following:
<!-- numbered-subquestions -->
1. How many rounds does radix sort need when it starts with the least significant digit?
2. If the student IDs are treated directly as integers for counting sort, why would the count array need many entries that are never used?
3. Based on the first two questions, which would you choose for sorting many fixed-length 8-digit student IDs: counting sort or radix sort? Why?
1. How many passes does radix sort need when starting with the least significant digit?
2. If counting sort treats each student ID directly as an integer, why would many counting entries go unused?
3. Based on your answers, which would you choose for sorting many eight-digit student IDs: counting sort or radix sort? Why?
??? success "Answer"
??? success "Reference answer"
1. A student ID has 8 digits, so 8 rounds are needed from the least significant to the most significant digit. Each round groups values only by 0–9.
1. Each ID has eight digits, so there are eight passes, from the least to the most significant digit. Each pass groups digits only by values 0 through 9.
2. Direct counting would require an entry for every possible 8-digit value, but only a small fraction of those values are actually assigned to students.
Most entries in the count array would remain 0.
2. Direct counting reserves an entry for every possible eight-digit value, but actual students use only a small fraction of them.
Most counts would remain 0.
3. Radix sort is the better choice. It uses the facts that the length is fixed and each digit has only 10 possible values, requiring only 8 rounds of stable grouping.
Counting sort, if it used the entire 8-digit ID as an integer index, would require count-array entries for many values that never occur.
3. Choose radix sort. It uses the fixed number of digits and the ten possible values per digit, requiring only eight stable grouping passes.
Counting sort using each entire eight-digit ID as an integer index would reserve entries for many values that never occur.
## Programming Exercises
## Programming exercises
### Sort an Array with Merge Sort
### Sorting an array with merge sort
Given an integer array `nums`, implement merge sort yourself, arrange its elements in nondecreasing order, and return the result. Do not call the language's built-in sorting function.
Given an integer array `nums`, implement merge sort yourself to arrange its elements in nondecreasing order and return the result. Do not call the language's built-in sorting function.
??? tip "Hints"
1. An interval of length at most 1 is already sorted
2. Divide the interval in half at its midpoint and recursively sort both halves
3. Use two pointers to merge the two sorted halves, then write the result back into the original array
1. An interval of length at most 1 is already sorted.
2. Split the interval in half at the midpoint and recursively sort each half.
3. Use two pointers to merge the sorted halves, then write the result back to the original array.
[LeetCode](https://leetcode.com/problems/sort-an-array/){ .rounded-button .exercise-button target="_blank" rel="noopener noreferrer" }
### Sort an Integer Array with Counting Sort
### Sorting an integer array with counting sort
You are given an integer array `nums` and a non-negative integer $K$. Every element of the array is between $0$ and $K$.
You are given an integer array `nums` and a nonnegative integer $K$. Every element lies between $0$ and $K$.
Implement counting sort, write the result back into `nums` in nondecreasing order, and return `nums`.
Do not determine the order by comparing elements, and do not call the language's built-in sorting function.
Implement counting sort, write the elements back into `nums` in nondecreasing order, and return `nums`.
Do not determine the order by comparing elements with one another, and do not use the language's built-in sorting function.
??? tip "Hints"
1. Because every element is between 0 and K, use each element's value directly as an index in the counting array
2. Scan nums once and increment the count at the corresponding position
3. Then scan the counting array from 0 to K; if the value x occurs a certain number of times, write x into nums that many consecutive times
1. Since every element is between 0 and K, its value can directly index the counting array.
2. First scan nums, incrementing the count at the corresponding position by 1.
3. Then scan the counting array from 0 through K. If x occurs a given number of times, write that many consecutive copies of x into nums.

View File

@@ -1,31 +1,31 @@
# Heap Sort
# Heap sort
!!! tip
Before reading this section, please ensure you have completed the "Heap" chapter.
Before reading this section, make sure you have completed the chapter on heaps.
<u>Heap sort</u> is an efficient sorting algorithm based on the heap data structure. We can implement heap sort using the heap construction and element removal operations introduced earlier.
<u>Heap sort</u> is an efficient sorting algorithm built on the heap data structure. We can implement it with the heap-building and removal operations we have already learned.
1. Input the array and build a min-heap, at which point the smallest element is at the heap top.
2. Continuously perform element removal operations and record the removed elements in order to obtain a sequence sorted in ascending order.
1. Build a min heap from the input array. The smallest element is now at the root.
2. Repeatedly remove the root and record the removed elements to obtain an ascending sequence.
Although the above method is feasible, it requires an additional array to save the popped elements, which is quite wasteful of space. In practice, we usually use a more elegant implementation method.
Although this works, it requires an extra array to store the removed elements, wasting space. In practice, we usually use a more elegant implementation.
## Algorithm Flow
## Algorithm steps
Assume the array length is $n$. The flow of heap sort is shown in the figure below.
For an array of length $n$, heap sort proceeds as shown below.
1. Input the array and build a max-heap. After completion, the largest element is at the heap top.
2. Swap the heap top element (first element) with the heap bottom element (last element). After the swap is complete, reduce the heap length by $1$ and increase the count of sorted elements by $1$.
3. Starting from the heap top element, perform a top-to-bottom heapify operation (sift down). After heapify is complete, the heap property is restored.
4. Repeat steps `2.` and `3.` After $n - 1$ rounds, the array is sorted.
1. Build a max heap from the input array. The largest element is now at the root.
2. Swap the root, the first element, with the last element of the heap. Reduce the heap's length by $1$ and increase the number of sorted elements by $1$.
3. Starting at the root, sift down to restore the heap property.
4. Repeat steps `2.` and `3.`. After $n - 1$ rounds, the array is sorted.
!!! tip
In fact, the element removal operation also includes steps `2.` and `3.`, with the additional step of removing the element.
In fact, removing the root of a heap also includes steps `2.` and `3.`, with the additional step of removing an element from the array.
=== "<1>"
![Heap sort steps](heap_sort.assets/heap_sort_step1.png)
![Steps of heap sort](heap_sort.assets/heap_sort_step1.png)
=== "<2>"
![heap_sort_step2](heap_sort.assets/heap_sort_step2.png)
@@ -60,14 +60,14 @@ Assume the array length is $n$. The flow of heap sort is shown in the figure bel
=== "<12>"
![heap_sort_step12](heap_sort.assets/heap_sort_step12.png)
In the code below, we use the same `sift_down()` function for top-to-bottom heapify as in the "Heap" chapter. It is worth noting that since the heap length decreases as the largest element is extracted, we need to add a length parameter $n$ to `sift_down()` to specify the current effective length of the heap. The code is as follows:
The implementation uses the same `sift_down()` function introduced in the heap chapter. Because the heap shrinks as maximum elements are extracted, add a length parameter $n$ to specify its current valid length. The code is as follows:
```src
[file]{heap_sort}-[class]{}-[func]{heap_sort}
```
## Algorithm Characteristics
## Algorithm properties
- **Time complexity is $O(n \log n)$; heap sort is non-adaptive**: Heap construction takes $O(n)$ time. Extracting the largest element from the heap takes $O(\log n)$ time, and this is repeated for a total of $n - 1$ rounds.
- **Space complexity is $O(1)$; heap sort is in-place**: A few pointer variables use $O(1)$ space. Element swapping and heapify are both performed on the original array.
- **Unstable sorting**: When swapping the heap top element and heap bottom element, the relative positions of equal elements may change.
- **Time complexity: $O(n \log n)$; not adaptive**. Building the heap takes $O(n)$ time. Extracting its maximum takes $O(\log n)$ time and is repeated $n - 1$ times.
- **Space complexity: $O(1)$; in-place**. A few pointer variables use $O(1)$ space. Swapping and sifting take place within the original array.
- **Not stable**. Swapping the root with the last element of the heap may change the relative order of equal elements.

View File

@@ -4,6 +4,6 @@
!!! abstract
Sorting is like a magic key that transforms chaos into order, enabling us to understand and process data more efficiently.
Sorting is like a magic key that turns chaos into order, helping us understand and process data more efficiently.
From simple ascending order to more complex classification schemes, sorting reveals the harmonious beauty of data.
From a simple ascending sequence to a complex arrangement by category, sorting reveals the harmonious beauty of data.

View File

@@ -1,46 +1,46 @@
# Insertion Sort
# Insertion sort
<u>Insertion sort</u> is a simple sorting algorithm that works very similarly to the process of manually sorting a deck of cards.
<u>Insertion sort</u> is a simple sorting algorithm that works much like arranging a hand of playing cards.
Specifically, we select a base element from the unsorted portion, compare it one by one with the elements in the sorted portion to its left, and insert it into the correct position.
Choose a base element from the unsorted section, compare it with the elements in the sorted section to its left, and insert it into the correct position.
The figure below illustrates how an element is inserted into an array. Let the base element be `base`. We need to shift all elements between the target index and `base` one position to the right, and then assign `base` to the target index.
The figure below shows how to insert an element into an array. Let the base element be `base`. Shift all elements between the target index and `base` one position to the right, then assign `base` to the target index.
![Single insertion operation](insertion_sort.assets/insertion_operation.png)
![A single insertion operation](insertion_sort.assets/insertion_operation.png)
## Algorithm Flow
## Algorithm steps
The overall flow of insertion sort is shown in the figure below.
The overall insertion sort process is shown below.
1. Initially, the first element of the array is already sorted.
2. Select the second element of the array as `base`, and after inserting it into the correct position, **the first 2 elements of the array are sorted**.
3. Select the third element as `base`, and after inserting it into the correct position, **the first 3 elements of the array are sorted**.
4. And so on. In the last round, select the last element as `base`, and after inserting it into the correct position, **all elements are sorted**.
1. Initially, the first element of the array is treated as sorted.
2. Select the second element as `base` and insert it into the correct position. **The first two elements are now sorted**.
3. Select the third element as `base` and insert it into the correct position. **The first three elements are now sorted**.
4. Continue in this way. In the final round, select the last element as `base` and insert it into the correct position. **All elements are now sorted**.
![Insertion sort flow](insertion_sort.assets/insertion_sort_overview.png)
![The insertion sort process](insertion_sort.assets/insertion_sort_overview.png)
Example code is as follows:
An implementation follows:
```src
[file]{insertion_sort}-[class]{}-[func]{insertion_sort}
```
## Algorithm Characteristics
## Algorithm properties
- **Time complexity of $O(n^2)$, adaptive sorting**: In the worst case, the insertion operations require $n - 1$, $n-2$, $\dots$, $2$, and $1$ iterations, respectively, summing to $(n - 1) n / 2$, so the time complexity is $O(n^2)$. When the data is already sorted, each insertion operation terminates early. When the input array is completely sorted, insertion sort achieves its best-case time complexity of $O(n)$.
- **Space complexity of $O(1)$, in-place sorting**: Pointers $i$ and $j$ use a constant amount of extra space.
- **Stable sorting**: During insertion, we place elements to the right of equal elements, so their relative order is unchanged.
- **Time complexity: $O(n^2)$; adaptive**. In the worst case, the insertion operations require $n - 1$, $n-2$, $\dots$, $2$, and $1$ iterations, totaling $(n - 1) n / 2$, so the time complexity is $O(n^2)$. For ordered data, an insertion can stop early. A fully sorted input achieves the best-case time complexity of $O(n)$.
- **Space complexity: $O(1)$; in-place**. Pointers $i$ and $j$ use constant extra space.
- **Stable**. Each element is inserted to the right of equal elements, preserving their order.
## Advantages of Insertion Sort
## Why use insertion sort?
The time complexity of insertion sort is $O(n^2)$, while the time complexity of quick sort, which we will learn about next, is $O(n \log n)$. Although insertion sort has a higher time complexity, **it is usually faster on small datasets**.
Insertion sort takes $O(n^2)$ time, while quick sort, which we will study shortly, takes $O(n \log n)$. Despite its higher time complexity, **insertion sort is usually faster for small datasets**.
This conclusion is similar to the one about when linear search and binary search are applicable. Algorithms such as quick sort, with $O(n \log n)$ complexity, are divide-and-conquer sorting algorithms and often involve more primitive operations. When the dataset is small, the values of $n^2$ and $n \log n$ are relatively close, so asymptotic complexity does not dominate; instead, the number of primitive operations per round becomes the deciding factor.
This resembles the comparison between linear and binary search. Algorithms such as quick sort, with $O(n \log n)$ time complexity, use divide and conquer and tend to involve more elementary operations. When the dataset is small, $n^2$ and $n \log n$ are relatively close, so asymptotic complexity is not the dominant factor; the number of elementary operations per round matters more.
In fact, the built-in sorting functions of many programming languages (such as Java) use insertion sort. The general idea is: for large arrays, use divide-and-conquer sorting algorithms such as quick sort; for short arrays, use insertion sort directly.
In fact, the built-in sorting functions of many programming languages, such as Java, use insertion sort. The general approach is to use a divide-and-conquer algorithm such as quick sort for long arrays and insertion sort directly for short ones.
Although bubble sort, selection sort, and insertion sort all have a time complexity of $O(n^2)$, in actual situations, **insertion sort is used significantly more frequently than bubble sort and selection sort**, mainly for the following reasons.
Although bubble sort, selection sort, and insertion sort all take $O(n^2)$ time, **insertion sort is used much more often in practice**, mainly for the following reasons.
- Bubble sort is implemented through element swaps, which require a temporary variable and involve 3 primitive operations; insertion sort is implemented through element assignment and requires only 1 primitive operation. Therefore, **bubble sort usually has higher computational overhead than insertion sort**.
- Selection sort has a time complexity of $O(n^2)$ in any case. **If given a set of partially ordered data, insertion sort is usually more efficient than selection sort**.
- Selection sort is unstable and cannot be applied to multi-level sorting.
- Bubble sort swaps elements, using a temporary variable and three elementary operations. Insertion sort shifts elements by assignment, requiring just one operation. **Bubble sort therefore usually has higher computational overhead**.
- Selection sort takes $O(n^2)$ time in every case. **For partially sorted data, insertion sort is usually more efficient than selection sort**.
- Selection sort is not stable and therefore cannot be used for multilevel sorting.

View File

@@ -1,23 +1,23 @@
# Merge Sort
# Merge sort
<u>Merge sort</u> is a sorting algorithm based on a divide-and-conquer strategy, consisting of the "divide" and "merge" phases shown in the figure below.
<u>Merge sort</u> is a divide-and-conquer sorting algorithm with the “division” and “merging” phases shown below.
1. **Divide phase**: Recursively split the array at the midpoint, reducing the problem of sorting a long array to the problem of sorting shorter arrays.
2. **Merge phase**: When a sub-array has length 1, stop dividing and start merging, continuously combining the shorter sorted sub-arrays on the left and right into a longer sorted array until the process is complete.
1. **Division**: recursively split the array at its midpoint, turning the problem of sorting a long array into problems of sorting shorter arrays.
2. **Merging**: stop dividing when a subarray has length 1, then repeatedly merge two shorter sorted arrays into one longer sorted array until the process is complete.
![Divide and merge phases of merge sort](merge_sort.assets/merge_sort_overview.png)
![The division and merging phases of merge sort](merge_sort.assets/merge_sort_overview.png)
## Algorithm Flow
## Algorithm steps
As shown in the figure below, the "divide phase" recursively splits the array from the midpoint into two sub-arrays from top to bottom.
As shown below, the division phase works from the top down, recursively splitting each array into two subarrays at its midpoint.
1. Calculate the array midpoint `mid`, recursively divide the left sub-array (interval `[left, mid]`) and right sub-array (interval `[mid + 1, right]`).
2. Repeat step `1.` recursively until a sub-array has length 1.
1. Calculate the midpoint `mid`, then recursively divide the left subarray, `[left, mid]`, and the right subarray, `[mid + 1, right]`.
2. Repeat step `1.` recursively until each subarray has length 1.
The "merge phase" merges the left and right sub-arrays into a sorted array from bottom to top. Note that merging starts from sub-arrays of length 1, so every sub-array involved in this phase is already sorted.
The merging phase works from the bottom up, combining the left and right subarrays into a sorted array. Merging begins with subarrays of length 1, so every subarray involved in this phase is already sorted.
=== "<1>"
![Merge sort steps](merge_sort.assets/merge_sort_step1.png)
![Steps of merge sort](merge_sort.assets/merge_sort_step1.png)
=== "<2>"
![merge_sort_step2](merge_sort.assets/merge_sort_step2.png)
@@ -46,28 +46,28 @@ The "merge phase" merges the left and right sub-arrays into a sorted array from
=== "<10>"
![merge_sort_step10](merge_sort.assets/merge_sort_step10.png)
The recursive order of merge sort is consistent with the post-order traversal of a binary tree.
Merge sort follows the same recursive order as a postorder traversal of a binary tree.
- **Post-order traversal**: First recursively traverse the left subtree, then recursively traverse the right subtree, and finally process the root node.
- **Merge sort**: First recursively process the left sub-array, then recursively process the right sub-array, and finally perform the merge.
- **Postorder traversal**: recurse into the left subtree, then the right subtree, and finally process the root.
- **Merge sort**: recurse into the left subarray, then the right subarray, and finally merge them.
The implementation of merge sort is shown in the code below. Note that the interval to be merged in `nums` is `[left, right]`, while the corresponding interval in `tmp` is `[0, right - left]`.
The implementation follows. The interval to merge in `nums` is `[left, right]`, while its corresponding interval in `tmp` is `[0, right - left]`.
```src
[file]{merge_sort}-[class]{}-[func]{merge_sort}
```
## Algorithm Characteristics
## Algorithm properties
- **Time complexity is $O(n \log n)$; merge sort is non-adaptive**: The divide phase produces a recursion tree of height $\log n$, and the total number of operations performed during merging at each level is $n$, so the overall time complexity is $O(n \log n)$.
- **Space complexity is $O(n)$; merge sort is not in-place**: The recursion depth is $\log n$, which uses $O(\log n)$ stack-frame space. The merge operation requires an auxiliary array, which uses $O(n)$ additional space.
- **Stable sort**: During merging, the relative order of equal elements remains unchanged.
- **Time complexity: $O(n \log n)$; not adaptive**. Division produces a recursion tree of height $\log n$. Merging performs a total of $n$ operations at each level, giving $O(n \log n)$ overall.
- **Space complexity: $O(n)$; not in-place**. The recursion depth is $\log n$, requiring $O(\log n)$ space for stack frames. Merging uses an auxiliary array requiring $O(n)$ extra space.
- **Stable**. Merging preserves the order of equal elements.
## Linked List Sorting
## Sorting linked lists
For linked lists, merge sort has significant advantages over other sorting algorithms, **and it can reduce the space complexity of the sorting task to $O(1)$**.
Merge sort has a significant advantage over other sorting algorithms for linked lists: **it can reduce the space complexity of sorting a linked list to $O(1)$**.
- **Divide phase**: Iteration can be used instead of recursion to split the linked list, thereby eliminating the stack-frame space used by recursion.
- **Merge phase**: In linked lists, node insertion and deletion require only pointer updates, so the merge phase (merging two short sorted linked lists into one longer sorted linked list) does not require creating an additional linked list.
- **Division**: use iteration instead of recursion to divide the list, eliminating the space needed for recursive stack frames.
- **Merging**: inserting and deleting linked-list nodes requires only changing references or pointers. Merging two short sorted lists into a longer one therefore needs no additional list.
The specific implementation details are quite complex, and interested readers can consult related materials for learning.
The implementation is fairly involved. Interested readers can consult further resources for details.

View File

@@ -1,15 +1,15 @@
# Quick Sort
# Quick sort
<u>Quick sort</u> is an efficient and widely used sorting algorithm based on the divide-and-conquer strategy.
<u>Quick sort</u> is an efficient, widely used sorting algorithm based on divide and conquer.
The core operation of quick sort is "sentinel partitioning", whose goal is to select an element as the "pivot", move all elements smaller than the pivot to its left, and move all elements larger than the pivot to its right. Specifically, the process is shown in the figure below.
Its core operation is “partitioning”: choose an array element as the “pivot,” move all smaller elements to its left, and move all larger elements to its right. The partitioning process is shown below.
1. Select the leftmost element as the pivot, and initialize two pointers `i` and `j` at the two ends of the array.
2. Enter a loop. In each round, use `i` (`j`) to find the first element larger (smaller) than the pivot, and then swap the two elements.
3. Repeat step `2.` until `i` and `j` meet, then swap the pivot into the boundary position between the two sub-arrays.
1. Choose the leftmost element as the pivot and initialize pointers `i` and `j` at the two ends of the array.
2. In a loop, use `i` to find the first element greater than the pivot and `j` to find the first element smaller than it, then swap those elements.
3. Repeat step `2.` until `i` and `j` meet. Finally, swap the pivot into the boundary between the two subarrays.
=== "<1>"
![Sentinel partitioning steps](quick_sort.assets/pivot_division_step1.png)
![Steps of partitioning](quick_sort.assets/pivot_division_step1.png)
=== "<2>"
![pivot_division_step2](quick_sort.assets/pivot_division_step2.png)
@@ -35,65 +35,65 @@ The core operation of quick sort is "sentinel partitioning", whose goal is to se
=== "<9>"
![pivot_division_step9](quick_sort.assets/pivot_division_step9.png)
After sentinel partitioning, the original array is divided into three parts: the left sub-array, the pivot, and the right sub-array, such that "any element in the left sub-array $\leq$ the pivot $\leq$ any element in the right sub-array". Therefore, we only need to sort the two sub-arrays next.
After partitioning, the original array has three parts: the left subarray, the pivot, and the right subarray. Every element in the left subarray is $\leq$ the pivot, which is $\leq$ every element in the right subarray. We now need only sort the two subarrays.
!!! note "Divide-and-conquer strategy of quick sort"
!!! note "Quick sort's divide-and-conquer strategy"
The essence of sentinel partitioning is to simplify the sorting problem of a longer array into the sorting problems of two shorter arrays.
Partitioning reduces the problem of sorting one long array to sorting two shorter arrays.
```src
[file]{quick_sort}-[class]{quick_sort}-[func]{partition}
```
## Algorithm Flow
## Algorithm steps
The overall flow of quick sort is shown in the figure below.
The overall quick sort process is shown below.
1. First, perform one "sentinel partitioning" on the original array to obtain the unsorted left sub-array and right sub-array.
2. Then, recursively perform "sentinel partitioning" on the left sub-array and right sub-array respectively.
3. Continue recursively until the sub-array length is 1, at which point sorting of the entire array is complete.
1. Partition the original array to obtain unsorted left and right subarrays.
2. Recursively partition the left and right subarrays.
3. Continue until each subarray has length 1, completing the sort.
![Quick sort flow](quick_sort.assets/quick_sort_overview.png)
![The quick sort process](quick_sort.assets/quick_sort_overview.png)
```src
[file]{quick_sort}-[class]{quick_sort}-[func]{quick_sort}
```
## Algorithm Characteristics
## Algorithm properties
- **Time complexity of $O(n \log n)$, non-adaptive sorting**: On average, sentinel partitioning produces $\log n$ recursive levels, and the total number of loop iterations across each level is $n$, so the overall time complexity is $O(n \log n)$. In the worst case, each round of sentinel partitioning splits an array of length $n$ into sub-arrays of lengths $0$ and $n - 1$. The recursion depth then reaches $n$, with $n$ loop iterations at each level, yielding an overall time complexity of $O(n^2)$.
- **Space complexity of $O(n)$, in-place sorting**: In the case where the input array is completely reversed, the worst recursive depth reaches $n$, using $O(n)$ stack frame space. The sorting operation is performed on the original array without the aid of an additional array.
- **Unstable sorting**: In the last step of sentinel partitioning, the pivot may be swapped to the right of an equal element.
- **Time complexity: $O(n \log n)$; not adaptive**. On average, partitioning produces $\log n$ recursive levels, with $n$ loop iterations in total at each level, giving $O(n \log n)$ time. In the worst case, each partition splits an array of length $n$ into subarrays of lengths $0$ and $n - 1$. The recursion reaches $n$ levels, each involving up to $n$ iterations, for $O(n^2)$ time overall.
- **Space complexity: $O(n)$; in-place**. A fully reverse-sorted input reaches the worst-case recursion depth of $n$, requiring $O(n)$ space for stack frames. Sorting takes place in the original array without an auxiliary array.
- **Not stable**. In the final partitioning step, the pivot may be swapped to the right of an equal element.
## Why Is Quick Sort Fast
## Why is quick sort quick?
As the name suggests, quick sort has clear efficiency advantages. Although its average time complexity is the same as that of "merge sort" and "heap sort", quick sort is usually faster in practice for the following reasons.
As its name suggests, quick sort has an efficiency advantage. Although its average time complexity matches that of merge sort and heap sort, it is usually faster, mainly for the following reasons.
- **The worst case is unlikely to occur**: Although the worst-case time complexity of quick sort is $O(n^2)$ and its performance is less predictable than that of merge sort, quick sort runs in $O(n \log n)$ time in the vast majority of cases.
- **High cache efficiency**: During sentinel partitioning, the system can load the entire sub-array into cache, so accessing elements is relatively efficient. By contrast, algorithms such as "heap sort" require non-contiguous access to elements and therefore do not enjoy this advantage.
- **Small constant factors**: Among the three algorithms above, quick sort performs the fewest comparisons, assignments, and swaps in total. This is similar to why "insertion sort" is faster than "bubble sort".
- **The worst case is unlikely**. Quick sort's worst-case time complexity is $O(n^2)$, making its performance less predictable than merge sort's, but it runs in $O(n \log n)$ time in the vast majority of cases.
- **Efficient cache use**. During partitioning, the system can load the whole subarray into cache, making element access efficient. Algorithms such as heap sort jump between elements and do not share this advantage.
- **Small constant factors**. Of these three algorithms, quick sort performs the fewest comparisons, assignments, swaps, and similar operations overall. This resembles the reason insertion sort is faster than bubble sort.
## Pivot Optimization
## Improving pivot selection
**Quick sort can become less time-efficient for certain inputs**. Consider an extreme example in which the input array is in completely descending order. Because we choose the leftmost element as the pivot, once sentinel partitioning is complete, the pivot is swapped to the far right of the array, leaving a left sub-array of length $n - 1$ and a right sub-array of length $0$. If this continues recursively, each round of sentinel partitioning produces one sub-array of length $0$, the divide-and-conquer strategy breaks down, and quick sort degenerates into an approximation of "bubble sort".
**Quick sort can become slower on certain inputs**. Consider a fully reverse-sorted array. Because the leftmost element is chosen as the pivot, partitioning moves it to the far right, leaving subarrays of lengths $n - 1$ and $0$. Continuing recursively produces a subarray of length $0$ after every partition. Divide and conquer becomes ineffective, and quick sort degenerates into a process resembling bubble sort.
To reduce the chance of this happening, **we can optimize the pivot selection strategy used in sentinel partitioning**. For example, we can choose a pivot at random. However, if we are unlucky and repeatedly pick poor pivots, performance can still be unsatisfactory.
To reduce this risk, **we can improve how the pivot is selected**. For example, choose a random element as the pivot. With bad luck, however, every pivot may still be poor, leading to disappointing performance.
It should be noted that programming languages usually generate "pseudo-random numbers". If we construct a specific test case against a pseudo-random sequence, quick sort can still suffer degraded performance.
Programming languages generally produce pseudorandom numbers. A test case constructed specifically for a pseudorandom sequence can still degrade quick sort's performance.
To improve further, we can choose three candidate elements from the array, usually the first, last, and middle elements, **and use the median of the three as the pivot**. This greatly increases the chance that the pivot is "neither too small nor too large". We can also choose more candidate elements to further improve the robustness of the algorithm. With this method, the probability that the time complexity degrades to $O(n^2)$ is significantly reduced.
For further improvement, choose three candidate elements, usually the first, last, and middle elements, **and use their median as the pivot**. This greatly increases the chance that the pivot is neither too small nor too large. We can use more candidates to improve robustness further. This approach greatly reduces the likelihood of degradation to $O(n^2)$.
Example code is as follows:
An implementation follows:
```src
[file]{quick_sort}-[class]{quick_sort_median}-[func]{partition}
```
## Recursive Depth Optimization
## Reducing recursion depth
**Quick sort may also use more space for certain inputs**. Consider a fully sorted input array. Let the length of the current sub-array in the recursion be $m$. Each round of sentinel partitioning produces a left sub-array of length $0$ and a right sub-array of length $m - 1$, which means each recursive call reduces the problem size by only one element. The recursion tree can therefore reach a height of $n - 1$, requiring $O(n)$ stack-frame space.
**Quick sort may use considerable space on certain inputs**. For a fully sorted input, let the current subarray have length $m$. Each partition produces a left subarray of length $0$ and a right subarray of length $m - 1$. Each recursive call therefore reduces the problem size by only one element, producing a recursion tree of height $n - 1$ and requiring $O(n)$ space for stack frames.
To prevent stack frames from accumulating, we can compare the lengths of the two sub-arrays after each round of sentinel partitioning, **and recurse only on the shorter one**. Because the shorter sub-array has length at most $n / 2$, this method ensures that the recursion depth does not exceed $\log n$, reducing the worst-case space complexity to $O(\log n)$. The code is shown below:
To prevent stack frames from accumulating, compare the two subarray lengths after each partition and **recurse only on the shorter one**. Since that subarray has length at most $n / 2$, the recursion depth is at most $\log n$, reducing the worst-case space complexity to $O(\log n)$. The code is as follows:
```src
[file]{quick_sort}-[class]{quick_sort_tail_call}-[func]{quick_sort}

View File

@@ -1,41 +1,41 @@
# Radix Sort
# Radix sort
The previous section introduced counting sort, which is suitable when the number of items $n$ is large but the value range $m$ is small. Suppose we need to sort $n = 10^6$ student IDs, each of which is an 8-digit number. Then the value range $m = 10^8$ is very large. Using counting sort would require a large amount of memory, whereas radix sort avoids this problem.
The previous section introduced counting sort, which suits a large number of elements $n$ with a small value range $m$. Suppose we need to sort $n = 10^6$ student IDs, each an $8$-digit number. The value range $m = 10^8$ is very large, so counting sort would require substantial memory. Radix sort avoids this problem.
<u>Radix sort</u> is based on the same core idea as counting sort: it also sorts by counting occurrences. Building on this, radix sort exploits the positional relationship among digits and sorts them one digit at a time to obtain the final result.
<u>Radix sort</u> shares counting sort's core idea of sorting by counting occurrences. It also uses the relative significance of digit positions, sorting one digit at a time to obtain the final order.
## Algorithm Flow
## Algorithm steps
Taking student ID data as an example, assume the lowest digit is the $1$st digit and the highest digit is the $8$th digit. The flow of radix sort is shown in the figure below.
For the student IDs, number the least significant digit as $1$ and the most significant as $8$. Radix sort proceeds as shown below.
1. Initialize the digit $k = 1$.
2. Perform "counting sort" on the $k$th digit of the student IDs. After completion, the data will be sorted from smallest to largest according to the $k$th digit.
3. Increase $k$ by $1$, then return to step `2.` and continue iterating until all digits are sorted, at which point the process ends.
1. Initialize the digit position $k = 1$.
2. Apply counting sort to the $k$th digit of each student ID. The data is now sorted in ascending order by its $k$th digit.
3. Increase the digit position $k$ by $1$ and return to step `2.`. Continue until all digit positions have been processed.
![Radix sort algorithm flow](radix_sort.assets/radix_sort_overview.png)
![The radix sort process](radix_sort.assets/radix_sort_overview.png)
Next, let us look at the code. For a number $x$ in base $d$, its $k$th digit $x_k$ can be obtained with the following formula:
Now consider the implementation. For a number $x$ in base $d$, its $k$th digit $x_k$ can be obtained with the following formula:
$$
x_k = \lfloor\frac{x}{d^{k-1}}\rfloor \bmod d
$$
Here, $\lfloor a \rfloor$ denotes rounding the floating-point number $a$ down, and $\bmod \: d$ denotes taking the remainder modulo $d$. For student ID data, $d = 10$ and $k \in [1, 8]$.
Here, $\lfloor a \rfloor$ rounds the floating-point value $a$ down, and $\bmod \: d$ takes the remainder modulo $d$. For the student IDs, $d = 10$ and $k \in [1, 8]$.
Additionally, we need to slightly modify the counting sort code to make it sort based on the $k$th digit of the number:
We also need to modify counting sort slightly so that it sorts by the $k$th digit:
```src
[file]{radix_sort}-[class]{}-[func]{radix_sort}
```
!!! question "Why start sorting from the lowest digit?"
!!! question "Why start with the least significant digit?"
In successive sorting passes, a later pass overrides the result of an earlier one. For example, if the first pass yields $a < b$ but the second yields $a > b$, then the result of the second pass prevails. Because higher-order digits have higher priority than lower-order digits, we should sort the lower digits first and then the higher digits.
In successive rounds, a later sort takes precedence over an earlier one. For example, if the first round orders two elements as $a < b$ but the second orders them as $a > b$, the second result replaces the first. Higher digits have greater priority, so lower digits must be sorted first.
## Algorithm Characteristics
## Algorithm properties
Compared with counting sort, radix sort is suitable for larger value ranges, **but only when the data can be represented with a fixed number of digits and that digit count is not too large**. For example, floating-point numbers are not well suited to radix sort because the digit count $k$ can be too large, potentially leading to time complexity $O(nk) \gg O(n^2)$.
Compared with counting sort, radix sort handles a larger range of values, **provided the data can be represented with a fixed number of digits and that number is not too large**. For example, floating-point numbers are unsuitable because their digit count $k$ may be so large that $O(nk) \gg O(n^2)$.
- **Time complexity of $O(nk)$, non-adaptive sorting**: Let the number of items be $n$, let the values be represented in base $d$, and let the maximum number of digits be $k$. Counting sort on one digit takes $O(n + d)$ time, so sorting all $k$ digits takes $O((n + d)k)$ time. In practice, $d$ and $k$ are usually relatively small, so the overall time complexity approaches $O(n)$.
- **Space complexity of $O(n + d)$, non-in-place sorting**: Same as counting sort, radix sort requires auxiliary arrays `res` and `counter` of lengths $n$ and $d$.
- **Stable sort**: When counting sort is stable, radix sort is also stable; when counting sort is unstable, radix sort cannot guarantee correct sorting results.
- **Time complexity: $O(nk)$; not adaptive**. For $n$ elements represented in base $d$ with at most $k$ digits, counting sort on one digit takes $O(n + d)$ time. Sorting all $k$ digits takes $O((n + d)k)$. Usually $d$ and $k$ are relatively small, so the complexity approaches $O(n)$.
- **Space complexity: $O(n + d)$; not in-place**. Like counting sort, radix sort requires arrays `res` and `counter` of lengths $n$ and $d$.
- **Stable**. Radix sort is stable when the counting sort used within it is stable. If counting sort is not stable, radix sort cannot guarantee a correctly sorted result.

View File

@@ -1,17 +1,17 @@
# Selection Sort
# Selection sort
<u>Selection sort</u> works very simply: in each round, it selects the smallest element from the unsorted interval and places it at the end of the sorted interval.
<u>Selection sort</u> works very simply: in each round, select the smallest element from the unsorted section and place it at the end of the sorted section.
Assume the array has length $n$. The procedure of selection sort is shown in the figure below.
For an array of length $n$, the algorithm proceeds as shown below.
1. Initially, all elements are unsorted, i.e., the unsorted (index) interval is $[0, n-1]$.
2. Select the smallest element in the interval $[0, n-1]$ and swap it with the element at index $0$. After completion, the first element of the array is sorted.
3. Select the smallest element in the interval $[1, n-1]$ and swap it with the element at index $1$. After completion, the first 2 elements of the array are sorted.
4. And so on. After $n - 1$ rounds of selection and swapping, the first $n - 1$ elements of the array are sorted.
5. The only remaining element must be the largest, so no further sorting is needed and the array is sorted.
1. Initially, all elements are unsorted, so the unsorted index interval is $[0, n-1]$.
2. Select the smallest element in $[0, n-1]$ and swap it with the element at index $0$. The first element is now sorted.
3. Select the smallest element in $[1, n-1]$ and swap it with the element at index $1$. The first two elements are now sorted.
4. Continue in this way. After $n - 1$ rounds of selection and swapping, the first $n - 1$ elements are sorted.
5. The remaining element must be the largest and needs no sorting. The array is now sorted.
=== "<1>"
![Selection sort steps](selection_sort.assets/selection_sort_step1.png)
![Steps of selection sort](selection_sort.assets/selection_sort_step1.png)
=== "<2>"
![selection_sort_step2](selection_sort.assets/selection_sort_step2.png)
@@ -43,16 +43,16 @@ Assume the array has length $n$. The procedure of selection sort is shown in the
=== "<11>"
![selection_sort_step11](selection_sort.assets/selection_sort_step11.png)
In the code, we use $k$ to track the smallest element within the unsorted interval:
In the code, $k$ tracks the smallest element in the unsorted section:
```src
[file]{selection_sort}-[class]{}-[func]{selection_sort}
```
## Algorithm Characteristics
## Algorithm properties
- **Time complexity $O(n^2)$, non-adaptive sorting**: The outer loop has $n - 1$ rounds in total. The inner loop runs $n - 1$ times in the first round and $1$ time in the last round. Thus, it runs $n - 1$, $n - 2$, $\dots$, $2$, and $1$ times across the rounds, summing to $\frac{n(n - 1)}{2}$.
- **Space complexity $O(1)$, in-place sorting**: Pointers $i$ and $j$ use a constant amount of extra space.
- **Unstable sorting**: As shown in the figure below, element `nums[i]` may be swapped to the right of an element equal to it, causing a change in their relative order.
- **Time complexity: $O(n^2)$; not adaptive**. The outer loop runs $n - 1$ times. The inner loop runs $n - 1$ times in the first round and $1$ time in the last, giving successive counts of $n - 1$, $n - 2$, $\dots$, $2$, and $1$, which sum to $\frac{n(n - 1)}{2}$.
- **Space complexity: $O(1)$; in-place**. Pointers $i$ and $j$ use constant extra space.
- **Not stable**. As shown below, `nums[i]` may be swapped to the right of an equal element, changing their relative order.
![Selection sort non-stability example](selection_sort.assets/selection_sort_instability.png)
![An example showing that selection sort is not stable](selection_sort.assets/selection_sort_instability.png)

View File

@@ -1,23 +1,23 @@
# Sorting Algorithm
# Sorting algorithms
A <u>sorting algorithm</u> arranges a set of data in a specific order. Sorting algorithms have extensive applications because ordered data can usually be searched, analyzed, and processed more efficiently.
A <u>sorting algorithm</u> arranges a dataset in a specified order. Sorting is widely used because ordered data is often easier to search, analyze, and process efficiently.
As shown in the figure below, the data being sorted can be integers, floating-point numbers, characters, strings, and so on. The sorting rule can be defined as needed, such as numerical order, ASCII order, or a custom rule.
As shown below, the data may consist of integers, floating-point numbers, characters, strings, and other types. The ordering rule can be chosen as needed: numerical magnitude, ASCII character order, or a custom rule.
![Data type and criterion examples](sorting_algorithm.assets/sorting_examples.png)
![Examples of data types and ordering rules](sorting_algorithm.assets/sorting_examples.png)
## Evaluation Dimensions
## Evaluation criteria
**Execution efficiency**: We expect the time complexity of sorting algorithms to be as low as possible, with a smaller total number of operations (reducing the constant factor in time complexity). For large data volumes, execution efficiency is particularly important.
**Efficiency**: We want low time complexity and few operations overall, corresponding to smaller constant factors in the complexity. Efficiency is especially important for large datasets.
**In-place property**: As the name implies, <u>in-place sorting</u> achieves sorting by operating directly on the original array without requiring additional auxiliary arrays, thus saving memory. Typically, in-place sorting involves fewer data movement operations and runs faster.
**In-place operation**: An <u>in-place sort</u> works directly on the original array without an auxiliary array, saving memory. It usually moves data fewer times and runs faster as well.
**Stability**: <u>Stable sorting</u> ensures that the relative order of equal elements in the array does not change after sorting is completed.
**Stability**: A <u>stable sort</u> preserves the relative order of equal elements in the array.
Stable sorting is a necessary condition for multi-level sorting scenarios. Suppose we have a table storing student information, where column 1 and column 2 are name and age, respectively. In this case, <u>unstable sorting</u> may cause the ordered nature of the input data to be lost:
Stable sorting is necessary for multilevel sorting. Suppose a table stores student names in its first column and ages in its second. An <u>unstable sort</u> may destroy the input's existing order:
```shell
# The input data is sorted by name
# The input is already sorted by name
# (name, age)
('A', 19)
('B', 18)
@@ -25,9 +25,9 @@ Stable sorting is a necessary condition for multi-level sorting scenarios. Suppo
('D', 19)
('E', 23)
# Suppose we use an unstable sorting algorithm to sort the list by age.
# In the result, the relative positions of ('D', 19) and ('A', 19) change,
# so the property that the input data is sorted by name is lost.
# Suppose an unstable algorithm sorts the list by age.
# The relative positions of ('D', 19) and ('A', 19) change,
# so the original ordering by name is lost
('B', 18)
('D', 19)
('A', 19)
@@ -35,12 +35,12 @@ Stable sorting is a necessary condition for multi-level sorting scenarios. Suppo
('E', 23)
```
**Adaptability**: <u>Adaptive sorting</u> can utilize the existing order information in the input data to reduce the amount of computation, achieving better time efficiency. The best-case time complexity of adaptive sorting algorithms is typically better than the average time complexity.
**Adaptiveness**: An <u>adaptive sort</u> uses ordering already present in the input to reduce computation and improve efficiency. Its best-case time complexity is usually better than its average complexity.
**Comparison-based or non-comparison**: <u>Comparison-based sorting</u> relies on comparison operators ($<$, $=$, $>$) to determine the relative order of elements, thereby sorting the entire array. Its worst-case time complexity has a lower bound of $\Omega(n \log n)$. <u>Non-comparison sorting</u> does not use comparison operators and can achieve a time complexity of $O(n)$, but its versatility is relatively limited.
**Comparison-based or not**: A <u>comparison-based sort</u> uses comparison operators ($<$, $=$, $>$) to determine the relative order of elements and sort the array. Its worst-case time complexity has a lower bound of $\Omega(n \log n)$. A <u>non-comparison sort</u> does not use comparison operators and can achieve $O(n)$ time, but is less broadly applicable.
## Ideal Sorting Algorithm
## The ideal sorting algorithm
**Fast, in-place, stable, adaptive, and broadly applicable**. Clearly, no sorting algorithm has been discovered to date that combines all of these characteristics. Therefore, when selecting a sorting algorithm, it is necessary to decide based on the specific characteristics of the data and the requirements of the problem.
**Fast, in-place, stable, adaptive, and broadly applicable**. No sorting algorithm with all these properties has yet been found. We must therefore choose according to the characteristics of the data and the requirements of the problem.
Next, we will examine various sorting algorithms and analyze their advantages and disadvantages based on the evaluation dimensions above.
Next, we will study different sorting algorithms and analyze their strengths and weaknesses using these criteria.

View File

@@ -1,47 +1,47 @@
# Summary
### Key Review
### Key takeaways
- Bubble sort achieves sorting by swapping adjacent elements. By adding a flag to enable early return, we can optimize the best-case time complexity of bubble sort to $O(n)$.
- In each round, insertion sort inserts an element from the unsorted portion into its correct position in the sorted portion. Although insertion sort has a time complexity of $O(n^2)$, it remains very popular for small sorting tasks because each operation is relatively lightweight.
- Quick sort relies on sentinel partitioning. In sentinel partitioning, repeatedly choosing the worst possible pivot can degrade the time complexity to $O(n^2)$. Choosing a median-based pivot or a random pivot can reduce the probability of this degradation. By recursing on the shorter subarray first, we can effectively reduce the recursion depth and optimize the space complexity to $O(\log n)$.
- Merge sort includes two phases: divide and merge, which typically embody the divide-and-conquer strategy. In merge sort, sorting an array requires creating auxiliary arrays, with a space complexity of $O(n)$; however, the space complexity of sorting a linked list can be optimized to $O(1)$.
- Bucket sort consists of three steps: distributing data into buckets, sorting within buckets, and merging results. It also embodies the divide-and-conquer strategy and is suitable for very large data volumes. The key to bucket sort is distributing data evenly.
- Counting sort is a special case of bucket sort, which achieves sorting by counting the number of occurrences of data. Counting sort is suitable for situations where the data volume is large but the data range is limited, and requires that data can be converted to positive integers.
- Radix sort achieves data sorting by sorting digit by digit, requiring that data can be represented as fixed-digit numbers.
- Overall, we hope to find a sorting algorithm that is efficient, stable, in-place, and adaptive. However, as with other data structures and algorithms, no sorting algorithm can satisfy all of these criteria at the same time. In practice, we need to choose the appropriate sorting algorithm based on the characteristics of the data.
- The figure below compares mainstream sorting algorithms in terms of efficiency, stability, in-place property, and adaptability.
- Bubble sort sorts by swapping adjacent elements. Adding a flag to stop early improves its best-case time complexity to $O(n)$.
- Insertion sort inserts one element from the unsorted section into its correct position in the sorted section each round. Although its time complexity is $O(n^2)$, its low operation count makes it popular for small datasets.
- Quick sort sorts through partitioning. Repeatedly choosing the worst pivot can degrade its time complexity to $O(n^2)$. Median or random pivot selection reduces this risk. Recursing on the shorter subarray reduces recursion depth and improves space complexity to $O(\log n)$.
- Merge sort has division and merging phases, exemplifying divide and conquer. Sorting an array requires an auxiliary array and $O(n)$ space, while sorting a linked list can be optimized to use $O(1)$ space.
- Bucket sort has three steps: distribute data into buckets, sort within each bucket, and combine the results. It also uses divide and conquer and suits very large datasets. The key is distributing data evenly.
- Counting sort is a special case of bucket sort that sorts by counting occurrences. It suits large datasets with a limited value range and requires data that can be converted to positive integers.
- Radix sort sorts one digit at a time and requires data that can be represented as numbers with a fixed number of digits.
- Ideally, a sorting algorithm would be efficient, stable, in-place, and adaptive. As with other data structures and algorithms, however, no single sorting algorithm meets all these requirements. In practice, choose one according to the data's properties.
- The figure below compares common sorting algorithms in efficiency, stability, in-place operation, and adaptiveness.
![Sorting algorithm comparison](summary.assets/sorting_algorithms_comparison.png)
![Comparison of sorting algorithms](summary.assets/sorting_algorithms_comparison.png)
### Q & A
**Q**: In what situations is the stability of sorting algorithms necessary?
**Q**: When is stability necessary in a sorting algorithm?
In reality, we may sort based on a certain attribute of objects. For example, students have two attributes: name and height. We want to implement multi-level sorting: first sort by name to get `(A, 180) (B, 185) (C, 170) (D, 170)`; then sort by height. Because the sorting algorithm is unstable, we may get `(D, 170) (C, 170) (A, 180) (B, 185)`.
We often sort objects by one of their attributes. For example, students have names and heights, and we want a multilevel sort. First sort by name to obtain `(A, 180) (B, 185) (C, 170) (D, 170)`, then sort by height. An unstable algorithm may produce `(D, 170) (C, 170) (A, 180) (B, 185)`.
We can see that students D and C have swapped positions, destroying the ordering by name, which is not what we want.
Students D and C have switched positions, breaking the ordering by name. This is not what we want.
**Q**: Can the order of "searching from right to left" and "searching from left to right" in sentinel partitioning be swapped?
**Q**: Can the right-to-left and left-to-right scans in partitioning be reversed?
No. When we use the leftmost element as the pivot, we must first "search from right to left" and then "search from left to right". This conclusion is somewhat counterintuitive; let's analyze the reason.
No. When the leftmost element is the pivot, the right-to-left scan must come first. This may seem counterintuitive, so let us examine why.
The last step of sentinel partitioning `partition()` is to swap `nums[left]` and `nums[i]`. After the swap is complete, the elements to the left of the pivot are all `<=` the pivot, **which requires that `nums[left] >= nums[i]` must hold before the last swap**. Suppose we first "search from left to right", then if we cannot find an element larger than the pivot, **we will exit the loop when `i == j`, at which point it may be that `nums[j] == nums[i] > nums[left]`**. In other words, the last swap operation will swap an element larger than the pivot to the leftmost end of the array, causing sentinel partitioning to fail.
The final step of `partition()` swaps `nums[left]` and `nums[i]`. Afterward, every element to the left of the pivot must be `<=` the pivot, **so `nums[left] >= nums[i]` must hold before that swap**. If we scan left to right first and fail to find a larger element, **the loop stops at `i == j`, where it is possible that `nums[j] == nums[i] > nums[left]`**. The final swap would then move an element larger than the pivot to the far left, causing partitioning to fail.
For example, given the array `[0, 0, 0, 0, 1]`, if we first "search from left to right", the array after sentinel partitioning is `[1, 0, 0, 0, 0]`, which is incorrect.
For example, given `[0, 0, 0, 0, 1]`, scanning left to right first produces `[1, 0, 0, 0, 0]` after partitioning, which is incorrect.
By the same reasoning, if we select `nums[right]` as the pivot, the order is reversed: we must first "search from left to right".
Conversely, if we choose `nums[right]` as the pivot, we must scan left to right first.
**Q**: Regarding the optimization of recursion depth in quick sort, why can selecting the shorter array ensure that the recursion depth does not exceed $\log n$?
**Q**: In the recursion-depth optimization for quick sort, why does choosing the shorter subarray keep the depth at most $\log n$?
Recursion depth is the number of recursive calls that have not yet returned. Each round of sentinel partitioning divides the original array into two sub-arrays. After this optimization, the sub-array selected for further recursion is at most half the length of the original array. In the worst case, if it is always half as long, the final recursion depth is $\log n$.
Recursion depth is the number of recursive calls that have not yet returned. Each partition divides the array into two subarrays. After the optimization, the subarray chosen for recursion is at most half the original length. Even in the worst case, where it is always exactly half, the depth is $\log n$.
Reviewing the original quick sort, we may continuously recurse on the longer array. In the worst case, it would be $n$, $n - 1$, $\dots$, $2$, $1$, with a recursion depth of $n$. Recursion depth optimization can avoid this situation.
In the original quick sort, we may repeatedly recurse on the larger subarray, with lengths $n$, $n - 1$, $\dots$, $2$, and $1$ in the worst case, giving depth $n$. The optimization prevents this.
**Q**: When all elements in the array are equal, is the time complexity of quick sort $O(n^2)$? How should this degenerate case be handled?
**Q**: If all array elements are equal, does quick sort take $O(n^2)$ time? How can we handle this degeneration?
Yes. In this case, the array can be partitioned into three parts through sentinel partitioning: less than, equal to, and greater than the pivot. We then recurse only on the less-than and greater-than parts. With this approach, an array whose elements are all equal can be sorted in just one round of sentinel partitioning.
Yes. In this case, consider partitioning into three sections: elements smaller than, equal to, and greater than the pivot. Recurse only on the smaller and greater sections. If all elements are equal, a single partition then completes the sort.
**Q**: Why is the worst-case time complexity of bucket sort $O(n^2)$?
**Q**: Why is bucket sort's worst-case time complexity $O(n^2)$?
In the worst case, all elements are distributed into the same bucket. If we use an $O(n^2)$ algorithm to sort these elements, the time complexity will be $O(n^2)$.
In the worst case, all elements fall into one bucket. If an $O(n^2)$ algorithm is used to sort that bucket, the overall time complexity is $O(n^2)$.