This commit is contained in:
krahets
2024-05-04 19:57:03 +08:00
parent 6d966b8b5d
commit 2395804410
27 changed files with 792 additions and 91 deletions
+33 -2
View File
@@ -276,7 +276,20 @@ comments: true
=== "Ruby"
```ruby title="bubble_sort.rb"
[class]{}-[func]{bubble_sort}
### 冒泡排序 ###
def bubble_sort(nums)
n = nums.length
# 外循环:未排序区间为 [0, i]
for i in (n - 1).downto(1)
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in 0...i
if nums[j] > nums[j + 1]
# 交换 nums[j] 与 nums[j + 1]
nums[j], nums[j + 1] = nums[j + 1], nums[j]
end
end
end
end
```
=== "Zig"
@@ -587,7 +600,25 @@ comments: true
=== "Ruby"
```ruby title="bubble_sort.rb"
[class]{}-[func]{bubble_sort_with_flag}
### 冒泡排序(标志优化)###
def bubble_sort_with_flag(nums)
n = nums.length
# 外循环:未排序区间为 [0, i]
for i in (n - 1).downto(1)
flag = false # 初始化标志位
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in 0...i
if nums[j] > nums[j + 1]
# 交换 nums[j] 与 nums[j + 1]
nums[j], nums[j + 1] = nums[j + 1], nums[j]
flag = true # 记录交换元素
end
end
break unless flag # 此轮“冒泡”未交换任何元素,直接跳出
end
end
```
=== "Zig"