This commit is contained in:
krahets
2024-04-12 03:16:45 +08:00
parent 8b8168bb31
commit b5f94abec9
10 changed files with 217 additions and 101 deletions
+15 -1
View File
@@ -253,7 +253,21 @@ comments: true
=== "Ruby"
```ruby title="insertion_sort.rb"
[class]{}-[func]{insertion_sort}
### 插入排序 ###
def insertion_sort(nums)
n = nums.length
# 外循环:已排序区间为 [0, i-1]
for i in 1...n
base = nums[i]
j = i - 1
# 内循环:将 base 插入到已排序区间 [0, i-1] 中的正确位置
while j >= 0 && nums[j] > base
nums[j + 1] = nums[j] # 将 nums[j] 向右移动一位
j -= 1
end
nums[j + 1] = base # 将 base 赋值到正确位置
end
end
```
=== "Zig"