Mik*_*nni 5 arrays delphi sorting integer delphi-10.1-berlin
我需要按整数字段对数组进行排序,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;
Run Code Online (Sandbox Code Playgroud)
有没有办法在一个单一的排序操作中进行这种排序?
试试这个,重点是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
));
Run Code Online (Sandbox Code Playgroud)
一个简短的测试显示它工作正常.