| ... | @@ -100,7 +100,19 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF | ... | @@ -100,7 +100,19 @@ pub fn PriorityQueue(comptime T: type, comptime Context: type, comptime compareF |
| 100 | const item = self.items[index]; | 100 | const item = self.items[index]; |
| 101 | self.items[index] = last; | 101 | self.items[index] = last; |
| 102 | self.len -= 1; | 102 | self.len -= 1; |
| 103 | siftDown(self, index); | 103 | |
| | 104 | if (index == 0) { |
| | 105 | siftDown(self, index); |
| | 106 | } else { |
| | 107 | const parent_index = ((index - 1) >> 1); |
| | 108 | const parent = self.items[parent_index]; |
| | 109 | if (compareFn(self.context, last, parent) == .gt) { |
| | 110 | siftDown(self, index); |
| | 111 | } else { |
| | 112 | siftUp(self, index); |
| | 113 | } |
| | 114 | } |
| | 115 | |
| 104 | return item; | 116 | return item; |
| 105 | } | 117 | } |
| 106 | | 118 | |
| ... | @@ -576,6 +588,20 @@ test "std.PriorityQueue: update same max heap" { | ... | @@ -576,6 +588,20 @@ test "std.PriorityQueue: update same max heap" { |
| 576 | try expectEqual(@as(u32, 1), queue.remove()); | 588 | try expectEqual(@as(u32, 1), queue.remove()); |
| 577 | } | 589 | } |
| 578 | | 590 | |
| | 591 | test "std.PriorityQueue: siftUp in remove" { |
| | 592 | var queue = PQlt.init(testing.allocator, {}); |
| | 593 | defer queue.deinit(); |
| | 594 | |
| | 595 | try queue.addSlice(&.{ 0, 1, 100, 2, 3, 101, 102, 4, 5, 6, 7, 103, 104, 105, 106, 8 }); |
| | 596 | |
| | 597 | _ = queue.removeIndex(std.mem.indexOfScalar(u32, queue.items[0..queue.len], 102).?); |
| | 598 | |
| | 599 | const sorted_items = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 100, 101, 103, 104, 105, 106 }; |
| | 600 | for (sorted_items) |e| { |
| | 601 | try expectEqual(e, queue.remove()); |
| | 602 | } |
| | 603 | } |
| | 604 | |
| 579 | fn contextLessThan(context: []const u32, a: usize, b: usize) Order { | 605 | fn contextLessThan(context: []const u32, a: usize, b: usize) Order { |
| 580 | return std.math.order(context[a], context[b]); | 606 | return std.math.order(context[a], context[b]); |
| 581 | } | 607 | } |