mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 01:06:30 +08:00
feat: add Swift codes for selection_sort article (#519)
This commit is contained in:
parent
4ce20f6bbc
commit
8bed60f0d7
2 changed files with 33 additions and 0 deletions
|
@ -47,6 +47,7 @@ let package = Package(
|
|||
.executable(name: "linear_search", targets: ["linear_search"]),
|
||||
.executable(name: "hashing_search", targets: ["hashing_search"]),
|
||||
// chapter_sorting
|
||||
.executable(name: "selection_sort", targets: ["selection_sort"]),
|
||||
.executable(name: "bubble_sort", targets: ["bubble_sort"]),
|
||||
.executable(name: "insertion_sort", targets: ["insertion_sort"]),
|
||||
.executable(name: "quick_sort", targets: ["quick_sort"]),
|
||||
|
@ -109,6 +110,7 @@ let package = Package(
|
|||
.executableTarget(name: "linear_search", dependencies: ["utils"], path: "chapter_searching", sources: ["linear_search.swift"]),
|
||||
.executableTarget(name: "hashing_search", dependencies: ["utils"], path: "chapter_searching", sources: ["hashing_search.swift"]),
|
||||
// chapter_sorting
|
||||
.executableTarget(name: "selection_sort", path: "chapter_sorting", sources: ["selection_sort.swift"]),
|
||||
.executableTarget(name: "bubble_sort", path: "chapter_sorting", sources: ["bubble_sort.swift"]),
|
||||
.executableTarget(name: "insertion_sort", path: "chapter_sorting", sources: ["insertion_sort.swift"]),
|
||||
.executableTarget(name: "quick_sort", path: "chapter_sorting", sources: ["quick_sort.swift"]),
|
||||
|
|
31
codes/swift/chapter_sorting/selection_sort.swift
Normal file
31
codes/swift/chapter_sorting/selection_sort.swift
Normal file
|
@ -0,0 +1,31 @@
|
|||
/**
|
||||
* File: selection_sort.swift
|
||||
* Created Time: 2023-05-28
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* 选择排序 */
|
||||
func selectionSort(nums: inout [Int]) {
|
||||
// 外循环:未排序区间为 [i, n-1]
|
||||
for i in nums.indices.dropLast() {
|
||||
// 内循环:找到未排序区间内的最小元素
|
||||
var k = i
|
||||
for j in nums.indices.dropFirst(i + 1) {
|
||||
if nums[j] < nums[k] {
|
||||
k = j // 记录最小元素的索引
|
||||
}
|
||||
}
|
||||
// 将该最小元素与未排序区间的首个元素交换
|
||||
nums.swapAt(i, k)
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
enum SelectionSort {
|
||||
/* Driver Code */
|
||||
static func main() {
|
||||
var nums = [4, 1, 3, 1, 5, 2]
|
||||
selectionSort(nums: &nums)
|
||||
print("选择排序完成后 nums = \(nums)")
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue