feat: add Swift codes for selection_sort article (#519)

This commit is contained in:
nuomi1 2023-05-28 17:51:35 +08:00 committed by GitHub
parent 4ce20f6bbc
commit 8bed60f0d7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 0 deletions

View file

@ -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"]),

View 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)")
}
}