mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 21:24:53 +08:00
Update the comments of bubble sort
and insertion sort
This commit is contained in:
@ -8,9 +8,9 @@ Author: timi (xisunyy@163.com)
|
||||
def bubble_sort(nums: list[int]) -> None:
|
||||
"""冒泡排序"""
|
||||
n = len(nums)
|
||||
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
# 外循环:未排序区间为 [0, i]
|
||||
for i in range(n - 1, 0, -1):
|
||||
# 内循环:冒泡操作
|
||||
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
|
||||
for j in range(i):
|
||||
if nums[j] > nums[j + 1]:
|
||||
# 交换 nums[j] 与 nums[j + 1]
|
||||
@ -20,10 +20,10 @@ def bubble_sort(nums: list[int]) -> None:
|
||||
def bubble_sort_with_flag(nums: list[int]) -> None:
|
||||
"""冒泡排序(标志优化)"""
|
||||
n = len(nums)
|
||||
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
# 外循环:未排序区间为 [0, i]
|
||||
for i in range(n - 1, 0, -1):
|
||||
flag = False # 初始化标志位
|
||||
# 内循环:冒泡操作
|
||||
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
|
||||
for j in range(i):
|
||||
if nums[j] > nums[j + 1]:
|
||||
# 交换 nums[j] 与 nums[j + 1]
|
||||
|
||||
@ -7,15 +7,15 @@ Author: timi (xisunyy@163.com)
|
||||
|
||||
def insertion_sort(nums: list[int]) -> None:
|
||||
"""插入排序"""
|
||||
# 外循环:base = nums[1], nums[2], ..., nums[n-1]
|
||||
# 外循环:已排序区间为 [0, i-1]
|
||||
for i in range(1, len(nums)):
|
||||
base = nums[i]
|
||||
j = i - 1
|
||||
# 内循环:将 base 插入到左边的正确位置
|
||||
# 内循环:将 base 插入到已排序区间 [0, i-1] 中的正确位置
|
||||
while j >= 0 and nums[j] > base:
|
||||
nums[j + 1] = nums[j] # 1. 将 nums[j] 向右移动一位
|
||||
nums[j + 1] = nums[j] # 将 nums[j] 向右移动一位
|
||||
j -= 1
|
||||
nums[j + 1] = base # 2. 将 base 赋值到正确位置
|
||||
nums[j + 1] = base # 将 base 赋值到正确位置
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
|
||||
Reference in New Issue
Block a user