Search code examples
delphidelphi-2010structure

Delphi - What object (multidimensional array, etc) will work?


I have a need to keep the top ten values in sorted order. My data structure is:

TMyRecord = record
  Number: Integer;
  Value: Float;
end

I will be calculating a bunch of float values. I need to keep the top 10 float values. Each value has an associated number. I want to add "sets"... If my float Value is higher than one of the top 10, it should add itself to the list, and then the "old" number 10, now 11, gets discarded. I should be able to access the list in (float value) sorted order...

It is almost like a TStringList, which maintains sorted order....

Is there anything like this already built into Delphi 2010?


Solution

  • You can use a combination of the generic list Generics.Collections.TList<TMyRecord> and insertion sort.

    Your data structure is like this

    TMyRecord = record
      Number: Integer;
      Value: Float;
    end;
    
    var
      Top10: TList<TMyRecord>;
    

    You'll need to use Generics.Collections to get the generic list.

    Instantiate it like this:

    Top10 := TList<TMyRecord>.Create;
    

    Use this function to add to the list:

    procedure Add(const Item: TMyRecord);
    var
      i: Integer;
    begin
      for i := 0 to Top10.Count-1 do 
        if Item.Value>Top10[i].Value then
        begin
          Top10.Insert(i, Item);
          Top10.Count := Min(10, Top10.Count);
          exit;
        end;
      if Top10.Count<10 then
        Top10.Add(Item);
    end;
    

    This is a simple implementation of insertion sort. The key to making this algorithm work is to make sure the list is always ordered.