This commit is contained in:
krahets
2024-03-21 04:22:07 +08:00
parent 35a07170c0
commit cfdb743939
52 changed files with 292 additions and 290 deletions
+6 -10
View File
@@ -142,14 +142,12 @@ comments: true
/* 冒泡排序 */
func bubbleSort(nums: inout [Int]) {
// 外循环:未排序区间为 [0, i]
for i in stride(from: nums.count - 1, to: 0, by: -1) {
for i in nums.indices.dropFirst().reversed() {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in stride(from: 0, to: i, by: 1) {
for j in 0 ..< i {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = tmp
nums.swapAt(j, j + 1)
}
}
}
@@ -404,14 +402,12 @@ comments: true
/* 冒泡排序(标志优化)*/
func bubbleSortWithFlag(nums: inout [Int]) {
// 外循环:未排序区间为 [0, i]
for i in stride(from: nums.count - 1, to: 0, by: -1) {
for i in nums.indices.dropFirst().reversed() {
var flag = false // 初始化标志位
for j in stride(from: 0, to: i, by: 1) {
for j in 0 ..< i {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = tmp
nums.swapAt(j, j + 1)
flag = true // 记录交换元素
}
}