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

pull/520/head
nuomi1 1 year ago committed by GitHub
parent 4ce20f6bbc
commit 8bed60f0d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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

@ -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…
Cancel
Save