From 8bed60f0d752b7091ed630f561611f3ecbe8a9af Mon Sep 17 00:00:00 2001 From: nuomi1 Date: Sun, 28 May 2023 17:51:35 +0800 Subject: [PATCH] feat: add Swift codes for selection_sort article (#519) --- codes/swift/Package.swift | 2 ++ .../chapter_sorting/selection_sort.swift | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 codes/swift/chapter_sorting/selection_sort.swift diff --git a/codes/swift/Package.swift b/codes/swift/Package.swift index 1190e534f..ac3c564f5 100644 --- a/codes/swift/Package.swift +++ b/codes/swift/Package.swift @@ -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"]), diff --git a/codes/swift/chapter_sorting/selection_sort.swift b/codes/swift/chapter_sorting/selection_sort.swift new file mode 100644 index 000000000..42f3c8cb8 --- /dev/null +++ b/codes/swift/chapter_sorting/selection_sort.swift @@ -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)") + } +}