如何对末尾为零的整数数组进行排序?

How to sort array of integers with zeros at the end?

我需要按整数字段对数组进行排序,1-n 排在开头,零排在最后: 0,0,3,1,2 -> 1,2,3,0,0

我不知道如何一次排序,所以我尝试了两种排序,但没有产生正确的结果:

它确实在末尾放了零,但它弄乱了 1-n 个有序项目:

0,0,3,1,2 ->(第一类)0,0,1,2,3 ->(第二类)2,3,1,0,0

procedure TForm2.Button1Click(Sender: TObject);
var
  Arr: TArray<integer>;
begin
  SetLength(Arr, 5);
  Arr[0] := 0;
  Arr[1] := 0;
  Arr[2] := 3;
  Arr[3] := 1;
  Arr[4] := 2;

  // First sort: Sort 1-n
  TArray.Sort<integer>(Arr, TComparer<integer>.Construct(function(const Left, Right: integer): Integer
    begin
      if Left < Right then
        Result := -1
      else if Left > Right then
        Result := 1
      else
        Result := 0;
    end
    ));

  // Second sort: Put zeros at the end
  TArray.Sort<integer>(Arr, TComparer<integer>.Construct(function(const Left, Right: integer): Integer
    begin
      if (Left = 0) and (right>0) then
        Result := 1
      else
        Result := 0;
    end
    ));
end;

有没有办法在一个单一的排序操作中完成这种排序?

只需修复您的比较函数,使其将 0 视为大于任何值。

未测试:

TArray.Sort<integer>(Arr, TComparer<integer>.Construct(function(const Left, Right: integer): Integer
  begin
    if Left = Right then
      Result := 0
    else if ((Left <> 0) and (Left < Right)) or (Right = 0) then
      Result := -1
    else 
      Result := 1;
  end
  ));

试试这个,重点是在 if-then-else 阶梯中先处理特殊 0 情况,然后再处理普通情况。

  TArray.Sort<integer>(Arr, TComparer<integer>.Construct(function(const Left, Right: integer): Integer
    begin
    if (Left = 0) and (Right = 0) then
      Result := 0
    else if (Left = 0) then
      Result := 1
    else if (Right = 0) then
      Result := -1
    else if (Left < Right) then
      Result := -1
    else if (Left > Right) then
      Result := 1
    else
      Result := 0;
    end
    ));

简短的测试表明它工作正常。