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

@@ -8,9 +8,9 @@ Author: timi (xisunyy@163.com)
def bubble_sort(nums: list[int]):
"""Bubble sort"""
n = len(nums)
# Outer loop: unsorted interval is [0, i]
# Outer loop: the unsorted range is [0, i]
for i in range(n - 1, 0, -1):
# Inner loop: swap the largest element in the unsorted interval [0, i] to the rightmost end of the interval
# Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
for j in range(i):
if nums[j] > nums[j + 1]:
# Swap nums[j] and nums[j + 1]
@@ -20,25 +20,25 @@ def bubble_sort(nums: list[int]):
def bubble_sort_with_flag(nums: list[int]):
"""Bubble sort (flag optimization)"""
n = len(nums)
# Outer loop: unsorted interval is [0, i]
# Outer loop: the unsorted range is [0, i]
for i in range(n - 1, 0, -1):
flag = False # Initialize flag
# Inner loop: swap the largest element in the unsorted interval [0, i] to the rightmost end of the interval
flag = False # Initialize the flag
# Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
for j in range(i):
if nums[j] > nums[j + 1]:
# Swap nums[j] and nums[j + 1]
nums[j], nums[j + 1] = nums[j + 1], nums[j]
flag = True # Record element swap
flag = True # Record that a swap occurred
if not flag:
break # No elements were swapped in this round of "bubbling", exit directly
break # Exit immediately if this pass made no swaps
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
nums = [4, 1, 3, 1, 5, 2]
bubble_sort(nums)
print("After bubble sort, nums =", nums)
print("After bubble sort, array =", nums)
nums1 = [4, 1, 3, 1, 5, 2]
bubble_sort_with_flag(nums1)
print("After bubble sort, nums =", nums1)
print("After bubble sort, array =", nums1)

View File

@@ -7,20 +7,20 @@ Author: krahets (krahets@163.com)
def bucket_sort(nums: list[float]):
"""Bucket sort"""
# Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
# Initialize k = n/2 buckets, expecting 2 elements per bucket
k = len(nums) // 2
buckets = [[] for _ in range(k)]
# 1. Distribute array elements into various buckets
# 1. Distribute the array elements among the buckets
for num in nums:
# Input data range is [0, 1), use num * k to map to index range [0, k-1]
# The input range is [0, 1); use num * k to map each value to an index in [0, k-1]
i = int(num * k)
# Add num to bucket i
buckets[i].append(num)
# 2. Sort each bucket
for bucket in buckets:
# Use built-in sorting function, can also replace with other sorting algorithms
# Use the built-in sorting function, or replace it with another sorting algorithm
bucket.sort()
# 3. Traverse buckets to merge results
# 3. Traverse the buckets to combine the results
i = 0
for bucket in buckets:
for num in bucket:
@@ -29,7 +29,7 @@ def bucket_sort(nums: list[float]):
if __name__ == "__main__":
# Assume input data is floating point, interval [0, 1)
# Assume the input consists of floating-point numbers in [0, 1)
nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37]
bucket_sort(nums)
print("After bucket sort, nums =", nums)

View File

@@ -7,17 +7,15 @@ Author: krahets (krahets@163.com)
def counting_sort_naive(nums: list[int]):
"""Counting sort"""
# Simple implementation, cannot be used for sorting objects
# 1. Count the maximum element m in the array
m = 0
for num in nums:
m = max(m, num)
# 2. Count the occurrence of each number
# counter[num] represents the occurrence of num
# Simple implementation; cannot be used to sort objects
# 1. Find the maximum array element m
m = max(nums)
# 2. Count the occurrences of each number
# counter[num] is the number of occurrences of num
counter = [0] * (m + 1)
for num in nums:
counter[num] += 1
# 3. Traverse counter, filling each element back into the original array nums
# 3. Traverse counter and fill the original array nums with the elements
i = 0
for num in range(m + 1):
for _ in range(counter[num]):
@@ -27,37 +25,37 @@ def counting_sort_naive(nums: list[int]):
def counting_sort(nums: list[int]):
"""Counting sort"""
# Complete implementation, can sort objects and is a stable sort
# 1. Count the maximum element m in the array
# Full implementation; stable and adaptable to sorting objects
# 1. Find the maximum array element m
m = max(nums)
# 2. Count the occurrence of each number
# counter[num] represents the occurrence of num
# 2. Count the occurrences of each number
# counter[num] is the number of occurrences of num
counter = [0] * (m + 1)
for num in nums:
counter[num] += 1
# 3. Calculate the prefix sum of counter, converting "occurrence count" to "tail index"
# counter[num]-1 is the last index where num appears in res
# 3. Compute prefix sums of counter to convert occurrence counts into end positions
# That is, counter[num]-1 is the index of the last occurrence of num in res
for i in range(m):
counter[i + 1] += counter[i]
# 4. Traverse nums in reverse order, placing each element into the result array res
# Initialize the array res to record results
# 4. Traverse nums in reverse and place each element in the result array res
# Initialize array res to store the result
n = len(nums)
res = [0] * n
for i in range(n - 1, -1, -1):
num = nums[i]
res[counter[num] - 1] = num # Place num at the corresponding index
counter[num] -= 1 # Decrement the prefix sum by 1, getting the next index to place num
# Use result array res to overwrite the original array nums
counter[num] -= 1 # Decrement the prefix sum by 1 to determine where to place the next occurrence of num
# Overwrite the original array nums with the result array res
for i in range(n):
nums[i] = res[i]
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4]
counting_sort_naive(nums)
print(f"After counting sort (unable to sort objects), nums = {nums}")
print(f"After counting sort (without support for objects), nums = {nums}")
nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4]
counting_sort(nums1)

View File

@@ -6,9 +6,9 @@ Author: krahets (krahets@163.com)
def sift_down(nums: list[int], n: int, i: int):
"""Heap length is n, start heapifying node i, from top to bottom"""
"""Sift down from node i in a heap of size n"""
while True:
# Determine the largest node among i, l, r, noted as ma
# Find the node with the largest value among i, l, and r, and store its index in ma
l = 2 * i + 1
r = 2 * i + 2
ma = i
@@ -16,29 +16,29 @@ def sift_down(nums: list[int], n: int, i: int):
ma = l
if r < n and nums[r] > nums[ma]:
ma = r
# If node i is the largest or indices l, r are out of bounds, no further heapification needed, break
# Stop if node i is largest or both child indices l and r are out of bounds
if ma == i:
break
# Swap two nodes
# Swap the two nodes
nums[i], nums[ma] = nums[ma], nums[i]
# Loop downwards heapification
# Continue sifting down
i = ma
def heap_sort(nums: list[int]):
"""Heap sort"""
# Build heap operation: heapify all nodes except leaves
# Build the heap by sifting down from every non-leaf node
for i in range(len(nums) // 2 - 1, -1, -1):
sift_down(nums, len(nums), i)
# Extract the largest element from the heap and repeat for n-1 rounds
# Extract the largest element from the heap, repeating for n-1 rounds
for i in range(len(nums) - 1, 0, -1):
# Swap the root node with the rightmost leaf node (swap the first element with the last element)
# Swap the root with the rightmost leaf on the last level (the first and last elements of the current heap)
nums[0], nums[i] = nums[i], nums[0]
# Start heapifying the root node, from top to bottom
# Sift down starting at the root
sift_down(nums, i, 0)
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
nums = [4, 1, 3, 1, 5, 2]
heap_sort(nums)

View File

@@ -7,18 +7,18 @@ Author: timi (xisunyy@163.com)
def insertion_sort(nums: list[int]):
"""Insertion sort"""
# Outer loop: sorted interval is [0, i-1]
# Outer loop: the sorted range is [0, i-1]
for i in range(1, len(nums)):
base = nums[i]
j = i - 1
# Inner loop: insert base into the correct position within the sorted interval [0, i-1]
# Inner loop: insert base at the correct position in the sorted range [0, i-1]
while j >= 0 and nums[j] > base:
nums[j + 1] = nums[j] # Move nums[j] to the right by one position
nums[j + 1] = nums[j] # Shift nums[j] one position to the right
j -= 1
nums[j + 1] = base # Assign base to the correct position
nums[j + 1] = base # Place base at the correct position
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
nums = [4, 1, 3, 1, 5, 2]
insertion_sort(nums)

View File

@@ -6,13 +6,13 @@ Author: timi (xisunyy@163.com), krahets (krahets@163.com)
def merge(nums: list[int], left: int, mid: int, right: int):
"""Merge left subarray and right subarray"""
# Left subarray interval is [left, mid], right subarray interval is [mid+1, right]
# Create a temporary array tmp to store the merged results
"""Merge the left and right subarrays"""
# The left subarray spans [left, mid], and the right subarray spans [mid+1, right]
# Create a temporary array tmp to store the merged result
tmp = [0] * (right - left + 1)
# Initialize the start indices of the left and right subarrays
# Initialize the starting indices of the left and right subarrays
i, j, k = left, mid + 1, 0
# While both subarrays still have elements, compare and copy the smaller element into the temporary array
# While both subarrays have elements remaining, compare them and copy the smaller element into the temporary array
while i <= mid and j <= right:
if nums[i] <= nums[j]:
tmp[k] = nums[i]
@@ -30,25 +30,25 @@ def merge(nums: list[int], left: int, mid: int, right: int):
tmp[k] = nums[j]
j += 1
k += 1
# Copy the elements from the temporary array tmp back to the original array nums at the corresponding interval
# Copy the elements of temporary array tmp back into the corresponding range of the original array nums
for k in range(0, len(tmp)):
nums[left + k] = tmp[k]
def merge_sort(nums: list[int], left: int, right: int):
"""Merge sort"""
# Termination condition
# Base case
if left >= right:
return # Terminate recursion when subarray length is 1
# Divide and conquer stage
mid = (left + right) // 2 # Calculate midpoint
merge_sort(nums, left, mid) # Recursively process the left subarray
merge_sort(nums, mid + 1, right) # Recursively process the right subarray
# Merge stage
return # Stop recursing when the subarray has at most one element
# Divide phase
mid = (left + right) // 2 # Calculate the midpoint
merge_sort(nums, left, mid) # Recurse on the left subarray
merge_sort(nums, mid + 1, right) # Recurse on the right subarray
# Merge phase
merge(nums, left, mid, right)
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
nums = [7, 3, 2, 6, 0, 1, 5, 4]
merge_sort(nums, 0, len(nums) - 1)

View File

@@ -9,28 +9,28 @@ class QuickSort:
"""Quick sort class"""
def partition(self, nums: list[int], left: int, right: int) -> int:
"""Sentinel partition"""
"""Two-pointer partitioning"""
# Use nums[left] as the pivot
i, j = left, right
while i < j:
while i < j and nums[j] >= nums[left]:
j -= 1 # Search from right to left for the first element smaller than the pivot
j -= 1 # Scan from right to left for the first element smaller than the pivot
while i < j and nums[i] <= nums[left]:
i += 1 # Search from left to right for the first element greater than the pivot
# Swap elements
i += 1 # Scan from left to right for the first element larger than the pivot
# Swap the elements
nums[i], nums[j] = nums[j], nums[i]
# Swap the pivot to the boundary between the two subarrays
# Swap the pivot into the boundary position between the two subarrays
nums[i], nums[left] = nums[left], nums[i]
return i # Return the index of the pivot
return i # Return the pivot index
def quick_sort(self, nums: list[int], left: int, right: int):
"""Quick sort"""
# Terminate recursion when subarray length is 1
# Stop recursing when the subarray has at most one element
if left >= right:
return
# Sentinel partition
# Two-pointer partitioning
pivot = self.partition(nums, left, right)
# Recursively process the left subarray and right subarray
# Recurse on the left and right subarrays
self.quick_sort(nums, left, pivot - 1)
self.quick_sort(nums, pivot + 1, right)
@@ -42,38 +42,38 @@ class QuickSortMedian:
"""Select the median of three candidate elements"""
l, m, r = nums[left], nums[mid], nums[right]
if (l <= m <= r) or (r <= m <= l):
return mid # m is between l and r
return mid # m lies between l and r
if (m <= l <= r) or (r <= l <= m):
return left # l is between m and r
return left # l lies between m and r
return right
def partition(self, nums: list[int], left: int, right: int) -> int:
"""Sentinel partition (median of three)"""
# Use nums[left] as the pivot
"""Two-pointer partitioning (median of three)"""
# Select the median of the leftmost, middle, and rightmost elements as the pivot
med = self.median_three(nums, left, (left + right) // 2, right)
# Swap the median to the array's leftmost position
# Swap the median into the leftmost position of the current subarray
nums[left], nums[med] = nums[med], nums[left]
# Use nums[left] as the pivot
i, j = left, right
while i < j:
while i < j and nums[j] >= nums[left]:
j -= 1 # Search from right to left for the first element smaller than the pivot
j -= 1 # Scan from right to left for the first element smaller than the pivot
while i < j and nums[i] <= nums[left]:
i += 1 # Search from left to right for the first element greater than the pivot
# Swap elements
i += 1 # Scan from left to right for the first element larger than the pivot
# Swap the elements
nums[i], nums[j] = nums[j], nums[i]
# Swap the pivot to the boundary between the two subarrays
# Swap the pivot into the boundary position between the two subarrays
nums[i], nums[left] = nums[left], nums[i]
return i # Return the index of the pivot
return i # Return the pivot index
def quick_sort(self, nums: list[int], left: int, right: int):
"""Quick sort"""
# Terminate recursion when subarray length is 1
# Stop recursing when the subarray has at most one element
if left >= right:
return
# Sentinel partition
# Two-pointer partitioning
pivot = self.partition(nums, left, right)
# Recursively process the left subarray and right subarray
# Recurse on the left and right subarrays
self.quick_sort(nums, left, pivot - 1)
self.quick_sort(nums, pivot + 1, right)
@@ -82,36 +82,36 @@ class QuickSortTailCall:
"""Quick sort class (recursion depth optimization)"""
def partition(self, nums: list[int], left: int, right: int) -> int:
"""Sentinel partition"""
"""Two-pointer partitioning"""
# Use nums[left] as the pivot
i, j = left, right
while i < j:
while i < j and nums[j] >= nums[left]:
j -= 1 # Search from right to left for the first element smaller than the pivot
j -= 1 # Scan from right to left for the first element smaller than the pivot
while i < j and nums[i] <= nums[left]:
i += 1 # Search from left to right for the first element greater than the pivot
# Swap elements
i += 1 # Scan from left to right for the first element larger than the pivot
# Swap the elements
nums[i], nums[j] = nums[j], nums[i]
# Swap the pivot to the boundary between the two subarrays
# Swap the pivot into the boundary position between the two subarrays
nums[i], nums[left] = nums[left], nums[i]
return i # Return the index of the pivot
return i # Return the pivot index
def quick_sort(self, nums: list[int], left: int, right: int):
"""Quick sort (recursion depth optimization)"""
# Terminate when subarray length is 1
# Stop when the subarray has at most one element
while left < right:
# Sentinel partition operation
# Perform two-pointer partitioning
pivot = self.partition(nums, left, right)
# Perform quick sort on the shorter of the two subarrays
# Apply quick sort to the shorter of the two subarrays
if pivot - left < right - pivot:
self.quick_sort(nums, left, pivot - 1) # Recursively sort the left subarray
left = pivot + 1 # Remaining unsorted interval is [pivot + 1, right]
left = pivot + 1 # The remaining unsorted range is [pivot + 1, right]
else:
self.quick_sort(nums, pivot + 1, right) # Recursively sort the right subarray
right = pivot - 1 # Remaining unsorted interval is [left, pivot - 1]
right = pivot - 1 # The remaining unsorted range is [left, pivot - 1]
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
# Quick sort
nums = [2, 4, 1, 0, 3, 5]
@@ -121,9 +121,9 @@ if __name__ == "__main__":
# Quick sort (median pivot optimization)
nums1 = [2, 4, 1, 0, 3, 5]
QuickSortMedian().quick_sort(nums1, 0, len(nums1) - 1)
print("After quick sort (median pivot optimization), nums =", nums1)
print("After quick sort (median pivot optimization), nums1 =", nums1)
# Quick sort (recursion depth optimization)
nums2 = [2, 4, 1, 0, 3, 5]
QuickSortTailCall().quick_sort(nums2, 0, len(nums2) - 1)
print("After quick sort (recursion depth optimization), nums =", nums2)
print("After quick sort (recursion depth optimization), nums2 =", nums2)

View File

@@ -6,51 +6,51 @@ Author: krahets (krahets@163.com)
def digit(num: int, exp: int) -> int:
"""Get the k-th digit of element num, where exp = 10^(k-1)"""
# Passing exp instead of k can avoid repeated expensive exponentiation here
"""Get the k-th digit of num, where exp = 10^(k-1)"""
# Passing exp instead of k avoids repeatedly performing expensive exponentiation here
return (num // exp) % 10
def counting_sort_digit(nums: list[int], exp: int):
"""Counting sort (based on nums k-th digit)"""
# Decimal digit range is 0~9, therefore need a bucket array of length 10
"""Counting sort (sort nums by the k-th digit)"""
# Decimal digits range from 0 to 9, so the bucket array needs length 10
counter = [0] * 10
n = len(nums)
# Count the occurrence of digits 0~9
# Count the occurrences of each digit from 0 to 9
for i in range(n):
d = digit(nums[i], exp) # Get the k-th digit of nums[i], noted as d
counter[d] += 1 # Count the occurrence of digit d
# Calculate prefix sum, converting "occurrence count" into "array index"
d = digit(nums[i], exp) # Get the k-th digit of nums[i] and store it in d
counter[d] += 1 # Count the occurrences of digit d
# Compute prefix sums to convert occurrence counts into array positions
for i in range(1, 10):
counter[i] += counter[i - 1]
# Traverse in reverse, based on bucket statistics, place each element into res
# Traverse in reverse and place each element into res according to the bucket counts
res = [0] * n
for i in range(n - 1, -1, -1):
d = digit(nums[i], exp)
j = counter[d] - 1 # Get the index j for d in the array
j = counter[d] - 1 # Get the destination index j for digit d in the array
res[j] = nums[i] # Place the current element at index j
counter[d] -= 1 # Decrease the count of d by 1
# Use result to overwrite the original array nums
counter[d] -= 1 # Decrease the count for d by 1
# Overwrite the original array nums with the result
for i in range(n):
nums[i] = res[i]
def radix_sort(nums: list[int]):
"""Radix sort"""
# Get the maximum element of the array, used to determine the maximum number of digits
# Get the largest array element to determine the maximum number of digits
m = max(nums)
# Traverse from the lowest to the highest digit
# Process digits from least significant to most significant
exp = 1
while exp <= m:
# Perform counting sort on the k-th digit of array elements
# Apply counting sort to the k-th digit of the array elements
# k = 1 -> exp = 1
# k = 2 -> exp = 10
# i.e., exp = 10^(k-1)
# That is, exp = 10^(k-1)
counting_sort_digit(nums, exp)
exp *= 10
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
# Radix sort
nums = [

View File

@@ -8,18 +8,18 @@ Author: krahets (krahets@163.com)
def selection_sort(nums: list[int]):
"""Selection sort"""
n = len(nums)
# Outer loop: unsorted interval is [i, n-1]
# Outer loop: the unsorted range is [i, n-1]
for i in range(n - 1):
# Inner loop: find the smallest element within the unsorted interval
# Inner loop: find the smallest element in the unsorted range
k = i
for j in range(i + 1, n):
if nums[j] < nums[k]:
k = j # Record the index of the smallest element
# Swap the smallest element with the first element of the unsorted interval
# Swap the smallest element with the first element of the unsorted range
nums[i], nums[k] = nums[k], nums[i]
"""Driver Code"""
"""Driver code"""
if __name__ == "__main__":
nums = [4, 1, 3, 1, 5, 2]
selection_sort(nums)