[Delphi (Object Pascal)] Delphi快速排序法对记录(record)进行排序 →→→→→进入此内容的聊天室

来自 , 2019-05-24, 写在 Delphi (Object Pascal), 查看 105 次.
URL http://www.code666.cn/view/a2802cad
  1. type
  2.   TCustomRecord = record
  3.     Key: WideString;
  4.     foo1:Int64;
  5.     foo2:TDatetime;
  6.     foo3:Extended;
  7.   end;
  8.   TCustomArray = array of TCustomRecord;
  9.  
  10. procedure QuickSort(var A: TCustomArray; L, R: Integer; var tmp: TCustomRecord);
  11. var
  12.   OrigL,
  13.   OrigR: Integer;
  14.   Pivot: WideString;
  15.   GoodPivot,
  16.   SortPartitions: Boolean;
  17. begin
  18.   if L<R then begin
  19.     Pivot:=A[L+Random(R-L)].Key;
  20.     OrigL:=L; //saving original bounds
  21.     OrigR:=R;
  22.     repeat
  23.       L:=OrigL; //restoring original bounds if we
  24.       R:=OrigR; //have chosen a bad pivot value
  25.       while L<R do begin
  26.         while (L<R) and (A[L].Key<Pivot) do Inc(L);
  27.         while (L<R) and (A[R].Key>=Pivot) do Dec(R);
  28.         if (L<R) then begin
  29.           tmp:=A[L];
  30.           A[L]:=A[R];
  31.           A[R]:=tmp;
  32.           Dec(R);
  33.           Inc(L);
  34.         end;
  35.       end;
  36.       if A[L].Key>=Pivot then Dec(L);                            //has we managed to choose
  37.       GoodPivot:=L>=OrigL;                                       //a good pivot value?
  38.       SortPartitions:=True;                                      //if so, then sort on
  39.       if not GoodPivot then begin                                //bad luck, the pivot is the smallest one in our range
  40.         GoodPivot:=True;                                         //let's presume that all the values are equal to pivot
  41.         SortPartitions:=False;                                   //then no need to sort it
  42.         for R := OrigL to OrigR do if A[R].Key<>Pivot then begin //we have at least one different value than our pivot
  43.           Pivot:=A[R].Key;                                       //so this will be our new pivot
  44.           GoodPivot:=False;                                      //we have to start again sorting this range
  45.           Break;
  46.         end;
  47.       end;
  48.     until GoodPivot;
  49.     if SortPartitions then begin
  50.       QuickSort(A, OrigL, L, tmp);
  51.       QuickSort(A, L+1, OrigR, tmp);
  52.     end;
  53.   end;
  54. end;
  55. //delphi/4528

回复 "Delphi快速排序法对记录(record)进行排序"

这儿你可以回复上面这条便签

captcha