如何对日期数组(TDate)进行排序?

时间:2014-04-25 10:25:55

标签: arrays delphi sorting delphi-7

我有一个array[0..99] of TDate,需要按降序对其进行排序。我无法在任何地方找到示例,甚至在StackOverflow上也找不到......

顺便说一句,并非所有数组项都有值。大多数情况下,数组填充10到30个值。我不需要“超快”的方式来做到这一点,但最简单/最简单的方式......

1 个答案:

答案 0 :(得分:0)

我不知道为什么你有一个TDates数组,而不是使用Delphi为你提供的TList,但我会假设你正在做一些测试项目,你需要一个快速而肮脏的方式对数组进行排序。这是一种方法,对于如此小的数组

来说,它将足够快
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.

确实建议使用其他一些数据结构(TList是最明显的选择)。这是一种方法:

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.