mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-12 15:36:05 +00:00
build
This commit is contained in:
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user