-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPathHeap.swift
103 lines (59 loc) · 1.99 KB
/
PathHeap.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
//
// PathHeap.swift
// SwiftStructures
//
// Created by Wayne Bishop on 8/9/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
public class PathHeap {
private var heap: Array<Path>
init() {
heap = Array<Path>()
}
//the number of frontier items
var count: Int {
return self.heap.count
}
//obtain the minimum path
func peek() -> Path? {
if heap.count > 0 {
return heap[0] //the shortest path
}
else {
return nil
}
}
//remove the minimum path
func deQueue() {
if heap.count > 0 {
heap.remove(at: 0)
}
}
//sort shortest paths into a min-heap (heapify)
func enQueue(_ key: Path) {
heap.append(key)
var childIndex: Float = Float(heap.count) - 1
var parentIndex: Int = 0
//calculate parent index
if childIndex != 0 {
parentIndex = Int(floorf((childIndex - 1) / 2))
}
var childToUse: Path
var parentToUse: Path
//use the bottom-up approach
while childIndex != 0 {
childToUse = heap[Int(childIndex)]
parentToUse = heap[parentIndex]
//swap child and parent positions
if childToUse.total < parentToUse.total {
heap.swapAt(parentIndex, Int(childIndex))
}
//reset indices
childIndex = Float(parentIndex)
if childIndex != 0 {
parentIndex = Int(floorf((childIndex - 1) / 2))
}
} //end while
} //end function
}