加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

数组 – 如何在结尾处用零对整数数组进行排序?

发布时间:2020-12-15 09:48:36 所属栏目:大数据 来源:网络整理
导读:我需要按整数字段对数组进行排序,其中1-n在开头排序,最后为0: 0,3,1,2 – 1,2,0 我不知道如何一次性排序,所以我尝试了两种,但它没有产生正确的结果: 它确实在最后添加了零,但它弄乱了1-n个有序物品: 0,2 – (第一类)0,3 – (第二类)2,0 procedure TForm2.
我需要按整数字段对数组进行排序,其中1-n在开头排序,最后为0:
0,3,1,2 – > 1,2,0

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

它确实在最后添加了零,但它弄乱了1-n个有序物品:

0,2 – > (第一类)0,3 – > (第二类)2,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,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,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
    ));

一个简短的测试显示它工作正常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读