Delphi排序String网格

时间:2015-04-06 21:51:37

标签: delphi

矩阵中的

(StringGrid)NxM以非递减顺序对每行的元素进行排序?

var
  Form1: TForm1;
  n,m:integer;
  I:integer;

implementation

{$R *.dfm}

procedure TForm1.btNapraviClick(Sender: TObject);
begin
  with StringGrid1 do
  begin
    n:=StrToInt(edN.text)+1;
    m:=StrToInt(edM.text)+1;
    ColCount:=n;
    RowCount:=m;

    for I:=0 to n-1 do Cells[I,0]:=IntToStr(I);
    for I:=1 to m-1 do Cells[0,I]:=IntToStr(I);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var J,P,K:integer;
begin
  with StringGrid1 do
  begin
    for I:=1 to n do
      for J:=1 to m-1 do
        for K:=J+1 to m do
        begin
          if StrToInt(Cells[I,J]) <= StrToInt(Cells[I,K]) then
          begin
            P:=StrToInt(Cells[I,J]);
            Cells[I,J]:=(Cells[I,K]);
            Cells[I,K]:=IntToStr(P);
          end;
        end;
  end;
end;

1 个答案:

答案 0 :(得分:3)

StringGrid中的每一行都来自TStrings,因此您可以为TStringList分配一行并对该行进行自定义排序。

以下是一些源代码:

首先我用随机数据填充网格:

procedure TForm60.FormCreate(Sender: TObject);
var
  i, j: Integer;
begin
  Randomize;

  with StringGrid1 do
  begin
    ColCount := 10;
    RowCount := 10;

    for i := 0 to ColCount - 1 do
      for j := 0 to RowCount - 1 do
        Cells[i, j] := IntToStr(Random(5000));
  end;
end;

然后在Button1.Click我按降序排序每一行:

function StringListSortCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := StrToIntDef(List[Index2], 0) - StrToIntDef(List[Index1], 0)
end;

procedure TForm60.Button1Click(Sender: TObject);
var
  i: Integer;
  Buffer: TStringList;
begin
  Buffer := TStringList.Create;
  for i := 0 to StringGrid1.RowCount - 1 do
  begin
    Buffer.Assign(StringGrid1.Rows[i]);
    Buffer.CustomSort(@StringListSortCompare);
    StringGrid1.Rows[i].Assign(Buffer);
  end;
  FreeAndNil(Buffer);
end;

由于我从List [Index1]中对List [Index2]的整数值进行subStract,因此列表将按降序排序。

结果:

<强>之前 enter image description here

<强>后 enter image description here

再次阅读你的问题后,我不确定你是否通过&#34;非减少秩序&#34;意味着增加秩序。如果是这样,只需实现这样的排序过程:

function StringListSortCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := StrToIntDef(List[Index1], 0) - StrToIntDef(List[Index2], 0)
end;