Home > Net >  Quicksort script works, but heapsort one doesn't
Quicksort script works, but heapsort one doesn't

Time:04-28

I've been using a quicksort function to sort my stringlists, but as an exercise I wanted to try and code an heapsort function too. Unfortunately it does not work and I can't understand why. The utility functions I use work (because I use them in the quicksort script too and trying both on a list the quicksort one works and the other doesn't)


    {------------------------------------------------------------------------------}
    Procedure Heapify(AList : TStringList; N, Root : Integer);
    Var
        Max, L, R : Integer;
    Begin
        Max := Root;
        L := (2 * Root)   1;
        R := (2 * Root)   2;
        If (L < N) And (ListSort(AList, Max, L) < 0 {function to compare strings, read as List[L]>List[Max]}) Then Max := L;
        If (R < N) And (ListSort(AList, Max, R) < 0) Then Max := R;
        If Max <> Root Then
        Begin
             ExchangeItems(AList, Root, Max); {Function to swap strings}
             Heapify(AList, N, Max);
        End;
    End;
    {------------------------------------------------------------------------------}
    Procedure HeapSortStringList(AList : TStringList);
    Var
        I : Integer;
    Begin
        For I := (AList.Count / 2) - 1 DownTo 0 Do Heapify(AList, AList.Count, I);
        For I := AList.Count - 1 DownTo 1 Do
        Begin
            ExchangeItems(AList, I, 0);
            Heapify(AList, I, 0);
        End;
    End;
    {------------------------------------------------------------------------------}

CodePudding user response:

How did you compile this code?

Note that compiler gives us message:

[dcc32 Error] Unit2.pas(175): E2010 Incompatible types: 'Integer' and 'Extended'

(AList.Count / 2) should be (AList.Count div 2) for integers

After this correction code becomes working.

  • Related