Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork5.7k
Description
Description
InGraphs/PrimMST.js
, the method_shiftDown
of classPriorityQueue
does not give the correct output when a node must be shifted to a left-child leaf without a right-child "brother", which results in a wrong behavior of methodpop
.
Expected Behavior
An example of a tree that produces the bug is given by the following array of nodes denoted by their priority:queue = [0, 1, 2]
ie
- root node of priority 0
- left leaf of priority 1
- right leaf of priority 0
If we call methodpop
on this queue, we expect to get the new tree:queue = [1, 2]
ie
- root node of priority 1
- left leaf of priority 2
Actual Behavior
In the case described above, we will get as output a tree represented by:queue = [2, 1]
ie
- root node of priority 2
- left leaf of priority 1
This violates the properties of the heap (we have 2 > 1 but a parent node should never have a bigger value than any of its children).
Steps to reproduce (if applicable)
- Add an export statement for class PriorityQueue in PrimMST.js
export { PriorityQueue }
- Add a test file
PrimMST.test.js
containing the following code
import { PriorityQueue} from '../PrimMST.js'test('Bug in pop method', () => { // create queue const queue = new PriorityQueue() queue.push(0, 0) queue.push(1, 1) queue.push(2, 2) // create expected queue const expectedQueue = new PriorityQueue() expectedQueue.push(1, 1) expectedQueue.push(2, 2) // result from popping element from the queue queue.pop() expect(queue).toEqual(expectedQueue)})
- Run the tests for PrimMST
npm test -- PrimMST.test.js
Additional information
This is due to the fact that in_shiftDown
, the children's priorities are computed under a singletry {} catch {}
statement, thus the priority of the left child is set toInfinity
if the right child does not exist.