Hola dandia28.
Una forma de ordenar un StringGrid por cualquier columna:
Código Delphi
[-]
implementation
...
type
TStrGrdExt = class(Grids.TStringGrid);
procedure TForm1.OrdenarGrid(StrGrd: TStringGrid; ACol: Integer);
var
i,j: Integer;
Fin: Boolean;
begin
with TStrGrdExt(StrGrd) do
begin
i:= FixedRows;
Fin:= False;
while not Fin and (i < RowCount -1 ) do
begin
Inc(i);
Fin:= True;
for j:= FixedRows to RowCount -2 do
if Cells[ACol,j] > Cells[ACol,j+1] then
begin
Fin:= False;
MoveRow(j, j+1);
end;
end;
end;
end;
Ejemplo de llamada:
Código Delphi
[-]
OrdenarGrid(StringGrid,1);
A fin de simplificar el ejemplo utilicé el método de ordenamiento
bubble sort, que para unos cientos de datos funcionará bién.
Pero para muchos cientos o varios miles te conviene implementar el método
shell sort o el
quick sort, siendo este último el más rápido.
Con el método
quick sort sería más o menos así:
Código Delphi
[-]
...
type
TStrGrdExt = class(Grids.TStringGrid);
procedure TForm1.OrdenarGrid(SG: TStringGrid; ACol,pri,ult: Integer);
var
i,j: Integer;
aux: string;
begin
with TStrGrdExt(SG) do
begin
i:= pri;
j:= ult;
aux:= Cells[ACol, (i + j) div 2];
repeat
while Cells[ACol, i] < aux do Inc(i);
while Cells[ACol, j] > aux do Dec(j);
if i <= j then
begin
if Cells[ACol,i] <> Cells[ACol,j] then
MoveRow(i, j)
else
Exit;
end;
until i > j;
if j > pri then OrdenarGrid(SG, ACol, pri, j);
if i < ult then OrdenarGrid(SG, ACol, i, ult);
end;
end;
Llamada:
Código Delphi
[-]
begin
OrdenarGrid(StringGrid, 1, 0, StringGrid.RowCount-1);
end;
Saludos.