Skip to content

max value decisions are different between Heap.max and Heap.replaceMax #439

Open
@iamhands0me

Description

@iamhands0me

In the Heap module, if the left max value is same as the right max value, the max variable will return the right one but the replaceMax function will replace the left one

struct Fruit: Comparable {
    let name: String
    var price: Int
    
    static func <(lhs: Fruit, rhs: Fruit) -> Bool {
        lhs.price < rhs.price
    }
}

var heap = Heap([
    Fruit(name: "🍎", price: 1),
    Fruit(name: "🍌", price: 10),
    Fruit(name: "🍊", price: 10)
])

if var maxPriceFruit = heap.max {
    maxPriceFruit.price -= 1
    
    heap.replaceMax(with: maxPriceFruit)
}

print(heap.unordered) // [Fruit(name: "🍎", price: 1), Fruit(name: "🍊", price: 9), Fruit(name: "🍊", price: 10)]

I think just changing

let maxNode = handle.maxValue(.leftMax, .rightMax)

to

let maxNode = handle.maxValue(.rightMax, .leftMax)

(same as popMax does) can fix the problem

Information

  • Package version: main branch

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions