feat: add Swift codes for heap_sort article (#520)

This commit is contained in:
nuomi1
2023-05-29 12:20:32 +08:00
committed by GitHub
parent 8bed60f0d7
commit 56a4385202
2 changed files with 57 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
/**
* File: heap_sort.swift
* Created Time: 2023-05-28
* Author: nuomi1 (nuomi1@qq.com)
*/
/* n i */
func siftDown(nums: inout [Int], n: Int, i: Int) {
var i = i
while true {
// i, l, r ma
let l = 2 * i + 1
let r = 2 * i + 2
var ma = i
if l < n, nums[l] > nums[ma] {
ma = l
}
if r < n, nums[r] > nums[ma] {
ma = r
}
// i l, r
if ma == i {
break
}
//
nums.swapAt(i, ma)
//
i = ma
}
}
/* */
func heapSort(nums: inout [Int]) {
//
for i in stride(from: nums.count / 2 - 1, through: 0, by: -1) {
siftDown(nums: &nums, n: nums.count, i: i)
}
// n-1
for i in stride(from: nums.count - 1, to: 0, by: -1) {
//
nums.swapAt(0, i)
//
siftDown(nums: &nums, n: i, i: 0)
}
}
@main
enum HeapSort {
/* Driver Code */
static func main() {
var nums = [4, 1, 3, 1, 5, 2]
heapSort(nums: &nums)
print("堆排序完成后 nums = \(nums)")
}
}