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:
nuomi1
2023-01-31 00:18:40 +08:00
committed by GitHub
parent 7f3752d306
commit f43f7a64b6
10 changed files with 525 additions and 5 deletions
+34 -2
View File
@@ -215,7 +215,21 @@ comments: true
=== "Swift"
```swift title="bubble_sort.swift"
/* 冒泡排序 */
func bubbleSort(nums: inout [Int]) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in stride(from: nums.count - 1, to: 0, by: -1) {
// 内循环:冒泡操作
for j in stride(from: 0, to: i, by: 1) {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = tmp
}
}
}
}
```
## 算法特性
@@ -424,5 +438,23 @@ comments: true
=== "Swift"
```swift title="bubble_sort.swift"
/* 冒泡排序(标志优化)*/
func bubbleSortWithFlag(nums: inout [Int]) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in stride(from: nums.count - 1, to: 0, by: -1) {
var flag = false // 初始化标志位
for j in stride(from: 0, to: i, by: 1) {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = tmp
flag = true // 记录交换元素
}
}
if !flag { // 此轮冒泡未交换任何元素,直接跳出
break
}
}
}
```