You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
/* *
* F i l e : h e a p . s w i f t
* C r e a t e d T i m e : 2 0 2 4 - 0 3 - 1 7
* A u t h o r : n u o m i 1 ( n u o m i 1 @ q q . c o m )
*/
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 {
/* D r i v e r C o d e */
static func main ( ) {
/* 初 始 化 堆 */
// S w i f t 的 H e a p 类 型 同 时 支 持 最 大 堆 和 最 小 堆
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 ( n l o g n )
let heap2 = Heap ( [ 1 , 3 , 2 , 5 , 4 ] )
print ( " \n 输入列表并建立堆后 " )
PrintUtil . printHeap ( queue : heap2 . unordered )
}
}