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 )
}
}