简体   繁体   中英

Delphi sorting String grid

in matrix(StringGrid) NxM sort the elements of each row in nondecreasing order?

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;

Each Row in a StringGrid decends from TStrings, so you can assign a row to a TStringList and do a custom sort on that one.

Here is some source code:

First I fill the grid with Random data:

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;

Then at Button1.Click I sort each row in descending order:

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;

Since I subStract the integer value of List[Index2] from List[Index1] the list becomes sorted descending.

And the result:

Before 在此处输入图片说明

After 在此处输入图片说明

After reading your question again I'm not sure if you by "nondecreasing order" mean increasing order. If so just implement the sort procedure like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM