Heapsort算法输出不正确

时间:2017-02-05 19:08:04

标签: vb.net binary-tree heapsort

首先,我很抱歉提出一个相当有限的问题。我理解答案可能不一定对其他人有益,但我一直试图找出问题无济于事。

运行代码时,不会出现错误,但输出与输入匹配。该算法的目的是输出排序的数组。

代码:

Dim heap() As Integer = {4, 9, 2, 1, 6, 3, 5, 7}
Dim sortedArray() As Integer
Dim listLength As Integer = heap.Length
Dim iteration As Integer
Dim max As Integer

Sub Main()

    Console.Write("Unsorted list: ")

    For i = 0 To 7
        Console.Write(heap(i))
        Console.Write(" ")
    Next

    Console.WriteLine(vbCrLf)

    HeapSort(heap)


    Console.Write("Sorted list: ")
    For i = 0 To 7
        Console.Write(heap(i))
        Console.Write(" ")
    Next

    Console.ReadKey()

End Sub

Sub HeapSort(ByRef heap() As Integer)
    Dim temp As Integer
    createheap(heap)
    For i = listLength To 1
        iteration = i
        temp = heap(iteration)
        heap(iteration) = heap(1)
        heap(1) = temp
        listLength = listLength - 1
        heapify(iteration, heap)
    Next

End Sub

Sub createheap(ByRef heap() As Integer)
    For i = listLength / 2 To 1
        iteration = i
        heapify(iteration, heap)
    Next
End Sub

Sub heapify(iteration As Integer, heap() As Integer)
    max = iteration
    Dim left As Integer = 2 * iteration
    Dim right As Integer = 2 * iteration + 1
    Dim temp As Integer

    If left <= listLength And heap(left) > heap(max) Then
        max = left
    Else
        max = iteration
    End If

    If right <= listlength And heap(right) > heap(max) Then
        max = right
    End If

    If max = Not iteration Then
        temp = heap(iteration)
        heap(iteration) = heap(max)
        heap(max) = temp

        heapify(max, heap)

    End If
End Sub

输出为:4 9 2 1 6 3 5 7

问题可以在何处找到?非常感谢,并允许我再次为可能被认为是不恰当的问题道歉。

0 个答案:

没有答案