-
Notifications
You must be signed in to change notification settings - Fork 276
/
Heap.swift
113 lines (69 loc) · 2.34 KB
/
Heap.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//
// Heap.swift
// SwiftStructures
//
// Created by Wayne Bishop on 9/7/17.
// Copyright © 2017 Arbutus Software Inc. All rights reserved.
//
import Foundation
/*
note: a generic heap (e.g. priority queue) algorithm. This class functions
as a min or max heap.
*/
class Heap<T: Comparable> {
private var items: Array<T>
private var heapType: HeapType
//min-heap default initialization
init(type: HeapType = .Min) {
items = Array<T>()
heapType = type
}
//number of items
var count: Int {
return self.items.count
}
//the min or max value
func peek() -> T? {
if items.count > 0 {
return items[0] //the min or max value
}
else {
return nil
}
}
//addition of new items
func enQueue(_ key: T) {
items.append(key)
var childIndex: Float = Float(items.count) - 1
var parentIndex: Int = 0
//calculate parent index
if childIndex != 0 {
parentIndex = Int(floorf((childIndex - 1) / 2))
}
var childToUse: T
var parentToUse: T
//use the bottom-up approach
while childIndex != 0 {
childToUse = items[Int(childIndex)]
parentToUse = items[parentIndex]
//heapify depending on type
switch heapType {
case .Min:
//swap child and parent positions
if childToUse <= parentToUse {
items.swapAt(parentIndex, Int(childIndex))
}
case .Max:
//swap child and parent positions
if childToUse >= parentToUse {
items.swapAt(parentIndex, Int(childIndex))
}
}
//reset indices
childIndex = Float(parentIndex)
if childIndex != 0 {
parentIndex = Int(floorf((childIndex - 1) / 2))
}
} //end while
} //end function
}