如何实现堆排序?

问题描述 投票:0回答:0

我的堆排序代码没有做它应该做的事。 例如

h = MaxHeap([1,9,5,7,8])
heapSort(h)
h.keys # [9 8 5 7 1]

显然没有排序。我只是找不到我的错误。我已经尝试了很多东西。它基本上是我在互联网上找到的伪代码,所以我不知道我做错了什么。如果有人能给我提示或向我解释如何改进我的代码,那就太好了。 提前致谢!

function left(i)
    return 2*i
end
function right(i)
    return 2*i + 1
end

struct MaxHeap
    keys::Vector{Int}
end

function MaxHeap(keys::Vector{Int})
    h = MaxHeap([])
    for k in keys
        push!(h.keys, k)
    end
    BuildMaxHeap(h)
    return h
end

function MaxHeapify(h::MaxHeap, i::Int)
    n = length(h.keys)
    l = left(i)
    r = right(i)
    if l <= n && h.keys[l] > h.keys[i]
        largest = l
    else
        largest = i
    end
    if r <= n && h.keys[r] > h.keys[largest]
        largest = r
    end
    if largest != i
        # swap A[i] and A[largest]
        h.keys[i], h.keys[largest] = h.keys[largest], h.keys[i]
        MaxHeapify(h, largest)
    end
end

function BuildMaxHeap(h::MaxHeap)
    n = length(h.keys)
    for i = (n ÷ 2):-1:1
        MaxHeapify(h, i)
    end
end

function heapSort(h::MaxHeap)
    BuildMaxHeap(h)
    n = length(h.keys)
    for i = n:-1:2
        h.keys[1], h.keys[i] = h.keys[i], h.keys[1]
        n = n - 1
        MaxHeapify(h, 1)
    end
end
data-structures julia heapsort
© www.soinside.com 2019 - 2024. All rights reserved.