mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-08 21:46:06 +00:00
feat: add Swift codes for chapter_sorting articles (#313)
* feat: add Swift codes for bubble_sort article * feat: add Swift codes for insertion_sort article * feat: add Swift codes for quick_sort article * feat: add Swift codes for merge_sort article * feat: add Swift codes for radix_sort * refactor: remove ^ operator
This commit is contained in:
@@ -178,7 +178,20 @@ comments: true
|
||||
=== "Swift"
|
||||
|
||||
```swift title="insertion_sort.swift"
|
||||
|
||||
/* 插入排序 */
|
||||
func insertionSort(nums: inout [Int]) {
|
||||
// 外循环:base = nums[1], nums[2], ..., nums[n-1]
|
||||
for i in stride(from: 1, to: nums.count, by: 1) {
|
||||
let base = nums[i]
|
||||
var j = i - 1
|
||||
// 内循环:将 base 插入到左边的正确位置
|
||||
while j >= 0, nums[j] > base {
|
||||
nums[j + 1] = nums[j] // 1. 将 nums[j] 向右移动一位
|
||||
j -= 1
|
||||
}
|
||||
nums[j + 1] = base // 2. 将 base 赋值到正确位置
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 算法特性
|
||||
|
||||
Reference in New Issue
Block a user