hello-algo/codes/swift/chapter_heap/heap.swift
nuomi1 7359a7cb4b
Review Swift codes (#1150)
* feat(swift): review for chapter_computational_complexity

* feat(swift): review for chapter_data_structure

* feat(swift): review for chapter_array_and_linkedlist

* feat(swift): review for chapter_stack_and_queue

* feat(swift): review for chapter_hashing

* feat(swift): review for chapter_tree

* feat(swift): add codes for heap article

* feat(swift): review for chapter_heap

* feat(swift): review for chapter_graph

* feat(swift): review for chapter_searching

* feat(swift): review for chapter_sorting

* feat(swift): review for chapter_divide_and_conquer

* feat(swift): review for chapter_backtracking

* feat(swift): review for chapter_dynamic_programming

* feat(swift): review for chapter_greedy

* feat(swift): review for utils

* feat(swift): update ci tool

* feat(swift): trailing closure

* feat(swift): array init

* feat(swift): map index
2024-03-20 21:15:39 +08:00

62 lines
1.6 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: heap.swift
* Created Time: 2024-03-17
* Author: nuomi1 (nuomi1@qq.com)
*/
import HeapModule
import utils
func testPush(heap: inout Heap<Int>, val: Int) {
heap.insert(val)
print("\n元素 \(val) 入堆后\n")
PrintUtil.printHeap(queue: heap.unordered)
}
func testPop(heap: inout Heap<Int>) {
let val = heap.removeMax()
print("\n堆顶元素 \(val) 出堆后\n")
PrintUtil.printHeap(queue: heap.unordered)
}
@main
enum _Heap {
/* Driver Code */
static func main() {
/* */
// Swift Heap
var heap = Heap<Int>()
/* */
testPush(heap: &heap, val: 1)
testPush(heap: &heap, val: 3)
testPush(heap: &heap, val: 2)
testPush(heap: &heap, val: 5)
testPush(heap: &heap, val: 4)
/* */
let peek = heap.max()
print("\n堆顶元素为 \(peek!)\n")
/* */
testPop(heap: &heap)
testPop(heap: &heap)
testPop(heap: &heap)
testPop(heap: &heap)
testPop(heap: &heap)
/* */
let size = heap.count
print("\n堆元素数量为 \(size)\n")
/* */
let isEmpty = heap.isEmpty
print("\n堆是否为空 \(isEmpty)\n")
/* */
// O(n) O(nlogn)
let heap2 = Heap([1, 3, 2, 5, 4])
print("\n输入列表并建立堆后")
PrintUtil.printHeap(queue: heap2.unordered)
}
}