mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-13 18:00:18 +08:00
Update the comments of bubble sort
and insertion sort
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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 赋值到正确位置
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user