Ver Mensaje Individual
  #8  
Antiguo 16-08-2012
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Reputación: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
Desempolvando los algoritmos de inserción binaria, podemos hacer una rutina que inserte los objetos en orden:

Código Delphi [-]
procedure InsertaOrdenado(Lista: TObjectList; Comparar: TListSortCompare; Item: Pointer);
var
  Primero, Ultimo, Central, Resultado: Integer;

begin
  Primero := 0;
  Ultimo := Lista.Count - 1;

  while Primero <= Ultimo do
  begin
    Central := (Primero + Ultimo) div 2;
    Resultado := Comparar(Item, Lista[Central]);

    if Resultado < 0
      then Ultimo := Central - 1
      else Primero := Central + 1;
  end;

  Lista.Insert(Primero, Item);
end;

Por ejemplo, puedes definir la función comparadora:

Código Delphi [-]
function CompararDocumentos(P1, P2: Pointer): Integer;
begin
  if TPersona(P1).Documento > TPersona(P2).Documento then
    Result := 1
  else if TPersona(P1).Documento = TPersona(P2).Documento then
    Result := 0
  else
    Result := -1;
end;

al momento de insertar:

Código Delphi [-]
P := TPersona.Create(StrToIntDef(txtDocumento.Text, 0),  txtNombre.Text);
InsertaOrdenado(ListaPersonas, CompararDocumentos, P);

// Saludos
Responder Con Cita