authorgravatar for bsvasan92@icloud.comBhargav Srinivasan <bsvasan92@icloud.com> 2020-09-22 03:46:13-07:00
committergravatar for bsvasan92@icloud.comBhargav Srinivasan <bsvasan92@icloud.com> 2020-09-22 03:46:13-07:00
log983830a4ae9955f95b46a4fb64d3914468226ccb
treea842d1d2b356abbf83d7ce60fb7bebadf22eced7
parenta5140cc9020f4e3649ccc14ca4317829ea289306

replace linearSearch with mem.indexOfScalar, return not found error, factor out siftUp from addUnchecked, use compareFn to decide siftUp/siftDown


1 files changed, 13 insertions(+), 20 deletions(-)

lib/std/priority_queue.zig+13-20
......@@ -49,7 +49,12 @@ pub fn PriorityQueue(comptime T: type) type {
4949
5050 fn addUnchecked(self: *Self, elem: T) void {
5151 self.items[self.len] = elem;
52 var child_index = self.len;
52 siftUp(self, self.len);
53 self.len += 1;
54 }
55
56 fn siftUp(self: *Self, start_index: usize) void {
57 var child_index = start_index;
5358 while (child_index > 0) {
5459 var parent_index = ((child_index - 1) >> 1);
5560 const child = self.items[child_index];
......@@ -61,7 +66,6 @@ pub fn PriorityQueue(comptime T: type) type {
6166 self.items[child_index] = parent;
6267 child_index = parent_index;
6368 }
64 self.len += 1;
6569 }
6670
6771 /// Add each element in `items` to the queue.
......@@ -190,27 +194,16 @@ pub fn PriorityQueue(comptime T: type) type {
190194 self.len = new_len;
191195 }
192196
193 fn linearSearch(elem: T, items: []const T) usize {
194 var found: usize = 0;
195 for (items) |item, i| {
196 if (item == elem) {
197 found = i;
198 break;
199 }
200 }
201 return found;
202 }
203
204197 pub fn update(self: *Self, elem: T, new_elem: T) !void {
205 var update_index: usize = linearSearch(elem, self.items);
198 var update_index: usize = std.mem.indexOfScalar(T, self.items, elem) catch |error| return error.ElementNotFound;
206199 assert (update_index >= 0 and update_index < self.items.len);
207 // Heapreplace:
208 // replace the item: self.items[update_index]= new_elem;
209 // swap the new item to the top of the heap: std.mem.swap(heap[0], heap[update_index]);
210 // sift up or down: which has been generically implemented as sift down: siftDown(self, 0)
200 const old_elem: T = self.items[update_index];
211201 self.items[update_index] = new_elem;
212 std.mem.swap(T, &self.items[0], &self.items[update_index]);
213 siftDown(self, 0);
202 if (self.compareFn(new_elem, old_elem)) {
203 siftUp(self, update_index);
204 } else {
205 siftDown(self, update_index);
206 }
214207 }
215208
216209 pub const Iterator = struct {