gpt4 book ai didi

arrays - 如何对末尾带有零的整数数组进行排序?

转载 作者:行者123 更新时间:2023-12-03 15:05:06 24 4
gpt4 key购买 nike

我需要按整数字段对数组进行排序,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;

有没有一种方法可以在一个单一的排序操作中进行这种排序?

最佳答案

试试这个,重点是先处理 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
));

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

关于arrays - 如何对末尾带有零的整数数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com