mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-11 06:56:06 +00:00
build
This commit is contained in:
@@ -111,7 +111,24 @@ comments: true
|
||||
=== "Go"
|
||||
|
||||
```go title="selection_sort.go"
|
||||
[class]{}-[func]{selectionSort}
|
||||
/* 选择排序 */
|
||||
func selectionSort(nums []int) {
|
||||
n := len(nums)
|
||||
// 外循环:未排序区间为 [i, n-1]
|
||||
for i := 0; i < n-1; i++ {
|
||||
// 内循环:找到未排序区间内的最小元素
|
||||
k := i
|
||||
for j := i + 1; j < n; j++ {
|
||||
if nums[j] < nums[k] {
|
||||
// 记录最小元素的索引
|
||||
k = j
|
||||
}
|
||||
}
|
||||
// 将该最小元素与未排序区间的首个元素交换
|
||||
nums[i], nums[k] = nums[k], nums[i]
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
@@ -141,7 +158,21 @@ comments: true
|
||||
=== "Swift"
|
||||
|
||||
```swift title="selection_sort.swift"
|
||||
[class]{}-[func]{selectionSort}
|
||||
/* 选择排序 */
|
||||
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)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
Reference in New Issue
Block a user