Debian Codegraph @

lib/mlrisc-lib/MLRISC/library/heap.sml

raw
1 (*
2 * This implements a priority queue using a heap
3 *
4 * -- Allen
5 *)
6
7 structure PriorityHeap :> PRIORITY_QUEUE =
8 struct
9 structure A = Array
10 exception EmptyPriorityQueue
11 exception Unimplemented
12
13 datatype 'a priority_queue =
14 HEAP of { less : 'a * 'a -> bool,
15 heap : 'a A.array,
16 size : int ref
17 }
18
19 fun createN(less,N,dummy) =
20 HEAP{less=less, heap = A.array(N,dummy), size = ref 0}
21
22 fun unimplemented() = raise Unimplemented
23
24 fun create _ = unimplemented()
25 fun merge _ = unimplemented()
26 fun mergeInto _ = unimplemented()
27 fun toList _ = unimplemented()
28
29 fun isEmpty (HEAP{ size = ref 0, ... }) = true
30 | isEmpty _ = false
31
32 fun clear (HEAP{ size, ... }) = size := 0
33
34 fun min(HEAP{ size = ref 0, ... }) = raise EmptyPriorityQueue
35 | min(HEAP{ heap, ... }) = A.sub(heap, 0)
36
37
38 fun insert(HEAP{ size, heap, less, ...}) x =
39 let val N = !size
40 fun siftup 0 = 0
41 | siftup i =
42 let val j = (i-1) div 2
43 val y = A.sub(heap,j)
44 in if less(x,y) then (A.update(heap,i,y); siftup j)
45 else i
46 end
47 in size := N + 1;
48 A.update(heap,siftup N,x)
49 end
50
51 fun siftDown(heap, less, N, i, x) =
52 let fun siftdown (i, x) =
53 let val j = i + i + 1
54 val k = j + 1
55 in if j >= N then i
56 else let val y = A.sub(heap,j)
57 in if k >= N then
58 if less(y,x) then go(i,x,j,y) else i
59 else
60 let val z = A.sub(heap,k)
61 in if less(y,x) then
62 if less(z,y) then go(i,x,k,z)
63 else go(i,x,j,y)
64 else if less(z,x) then go(i,x,k,z)
65 else i
66 end
67 end
68 end
69 and go(i,x,j,y) = (A.update(heap,i,y); siftdown(j,x))
70 val pos_x = siftdown(i, x)
71 in A.update(heap, pos_x, x);
72 pos_x
73 end
74
75 fun deleteMin(HEAP{ size = ref 0, ...}) = raise EmptyPriorityQueue
76 | deleteMin(HEAP{ size, heap, less, ...}) =
77 let val N = !size - 1
78 val min = A.sub(heap,0)
79 val x = A.sub(heap,N)
80 val x_pos = siftDown(heap, less, N, 0, x)
81 in size := N;
82 min
83 end
84
85 fun fromList less data =
86 let val heap = A.fromList data
87 val N = A.length heap
88 fun make_heap ~1 = ()
89 | make_heap i =
90 (siftDown(heap,less,N,i,A.sub(heap,i)); make_heap(i-1))
91 in if N >= 2 then make_heap((N+1) div 2) else ();
92 HEAP{ less = less, heap = heap, size = ref N }
93 end
94 end