-
Notifications
You must be signed in to change notification settings - Fork 0
/
priorityQueue.jl
44 lines (40 loc) · 1.06 KB
/
priorityQueue.jl
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
function queue!(heap::Vector{T}, key::T) where {T}
push!(heap,key)
swim!(heap)
end
function dequeue!(heap::Vector{T}) where {T}
if length(heap) > 1
last = length(heap)
heap[1], heap[last] = heap[last], heap[1]
end
removedKey = pop!(heap)
sink!(heap)
return removedKey
end
up(i::Int) = i >>> 1
left(i::Int) = i << 1
right(i::Int) = (i << 1) + 1
function swim!(heap::Vector{T}) where {T}
node = length(heap)
upper = up(node)
while node > 1 && heap[node] < heap[upper]
heap[node], heap[upper] = heap[upper], heap[node]
node = upper
upper = up(node)
end
end
function sink!(heap::Vector{T}) where {T}
node = 1
lft = left(node)
rght = right(node)
last = length(heap)
while lft <= last
minChild = lft
if lft < last && heap[rght] < heap[lft]; minChild = rght end
if heap[node] < heap[minChild]; break; end
heap[node], heap[minChild] = heap[minChild], heap[node]
node = minChild
lft = left(node)
rght = right(node)
end
end