2015-04-06 66 views
0

in matrix(StringGrid)NxM按非遞減順序排序每一行的元素?Delphi排序字符串網格

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; 
+2

不知道你的問題是什麼。你爲什麼要測試'<='而不是'<?如果它們相等,則不必要地交換兩個相等的值。此外,沒有理由讓P成爲一個整數或做一個轉換;只是把它做成一個字符串。你知道你沒有定義一個變量'I:Integer;'?我還會使用調試器來確保m和n不是基於零的,並且在這些內部循環中沒有錯誤的錯誤。 –

+0

你是對的<,我的錯。但是我把declard看作是整數,就像全局變量一樣。 – Malone

回答

2

中的每一行StringGrid從字符串列表decends,這樣你就可以分配行到的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]中SubStract List [Index2]的整數值,該列表變爲按降序排序。

而結果:

以前 enter image description here

enter image description here

再次閱讀您的問題後,我不知道,如果你是 「非減序」 的意思是爲了增加。如果是這樣,只是實施這樣的排序程序:

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

非常感謝你:))) – Malone

+0

@Malone如果你喜歡答案,請接受它 –