Update the comments of bubble sort

and insertion sort
This commit is contained in:
krahets
2023-05-22 23:05:37 +08:00
parent 5b406666d8
commit f6d290d903
36 changed files with 119 additions and 119 deletions

View File

@@ -6,9 +6,9 @@
/* 冒泡排序 */
func bubbleSort(nums: inout [Int]) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
// 外循环:未排序区间为 [0, i]
for i in stride(from: nums.count - 1, to: 0, by: -1) {
// 内循环:冒泡操作
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in stride(from: 0, to: i, by: 1) {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
@@ -22,7 +22,7 @@ func bubbleSort(nums: inout [Int]) {
/* 冒泡排序(标志优化)*/
func bubbleSortWithFlag(nums: inout [Int]) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
// 外循环:未排序区间为 [0, i]
for i in stride(from: nums.count - 1, to: 0, by: -1) {
var flag = false // 初始化标志位
for j in stride(from: 0, to: i, by: 1) {

View File

@@ -6,16 +6,16 @@
/* 插入排序 */
func insertionSort(nums: inout [Int]) {
// 外循环:base = nums[1], nums[2], ..., nums[n-1]
// 外循环:已排序元素数量为 1, 2, ..., n
for i in stride(from: 1, to: nums.count, by: 1) {
let base = nums[i]
var j = i - 1
// 内循环:将 base 插入到左边的正确位置
// 内循环:将 base 插入到已排序部分的正确位置
while j >= 0, 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 赋值到正确位置
}
}