Search code examples
arraysdelphisortingdelphi-7

How to sort an array of dates (TDate) descending?


I have an array[0..99] of TDate and need to sort it, in descending order. I can't find an example anywhere, not even here on StackOverflow...

Btw, not all array items have a value. Most of the time, the array is filled with 10 to 30 values. I do not need a "super fast" way to do this, but the simplest / easier way...


Solution

  • I don't know why you have an array of TDates, rather than using a TList that Delphi provides for you, but I'll assume you are making some sort of test project, and you just need a quick and dirty way to sort your array. Here's a way to do it that will be more than quick enough for such a small array

    program Project1;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      System.SysUtils, DateUtils;
    
    var
      A : array[0..99] of TDateTime;
      T : TDateTime; //Used to exchange dates
      I,J : integer;
    
    begin
      //Initialize with some test data:
      for I := 0 to 99 do
        A[I] := DateOf(Now) - 365 + random(365);
    
      //Output the unsorted list:
      for I := 0 to 99 do
        writeln(DateToStr(A[I]));
      readln;
    
      //Here's our sorting algorithm (Bubble Sort, probably the easiest sorting algorithm to
      //understand, and the quickes to implement - but the worst sorting algorithm in actual use
      for I := 0 to 98 do //One less than the max index, but you really should use some constants
        for J := I+1 to 99 do //Up to the max index
          if A[I] < A[J] then //Change < to > to sort in ascending order
          begin
            T := A[I];     //We'll be overwriting A[I], so we should store the value
            A[I] := A[J];  //Here we overwrite A[I] with A[J]
            A[J] := T;     //And here we put T back in the new position
          end;
    
      //Output the sorted list:
      for I := 0 to 99 do
        writeln(DateToStr(A[I]));
      readln;
    end.
    

    I would really recommend using some other data structure (TList being the most obvious choice). Here's a way to do that:

    program Project1;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      System.SysUtils, DateUtils, generics.collections;
    
    var
      A : TList<TDate>;
      I : integer;
      T : TDate; 
    
    begin
      A := TList<TDate>.Create;
      try
        for I := 0 to 99 do
          A.Add(DateOf(Now) - 365 + random(365));
    
        A.Sort; //Sorts in ascending order by default
        A.Reverse; //But you wanted descending order, so we'll reverse the list
    
        for T in A do
          writeln(DateToStr(T));
        readln;
      finally
        A.Free;
      end;
    end.