Reputation: 11
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;
Upvotes: 0
Views: 6938
Reputation: 6402
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;
Upvotes: 3