Google
 

Sunday, October 28, 2007

QuickSort Sorting Algorithm in Delphi

One of the common problems in programming is to sort an array of values in some order (ascending or descending).

While there are many "standard" sorting algorithms, QuickSort is one of the fastest. Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.

QuickSort Algorith

The basic concept is to pick one of the elements in the array, called a pivot. Around the pivot, other elements will be rearranged. Everything less than the pivot is moved left of the pivot - into the left partition. Everything greater than the pivot goes into the right partition. At this point each partition is recursively "quick sorted".

Here's QuickSort algorithm implemented in Delphi:

procedure QuickSort(var A: array of Integer; iLo, iHi: Integer) ;
var
___Lo, Hi, Pivot, T: Integer;
begin
___Lo := iLo;
___ Hi := iHi;
___Pivot := A[(Lo + Hi) div 2];
___repeat
______while A[Lo] <>do Inc(Lo) ;
______while A[Hi] > Pivot do Dec(Hi) ;
______if Lo <= Hi then
______begin
_________T := A[Lo];
_________A[Lo] := A[Hi];
_________A[Hi] := T;______
_________Inc(Lo) ;
_________Dec(Hi) ;
______end;
___until Lo > Hi;
___if Hi > iLo then QuickSort(A, iLo, Hi) ;
___if Lo <>then QuickSort(A, Lo, iHi) ;
end;

Usage:

var
___intArray : array of integer;
begin
___SetLength(intArray,10) ;

//Add values to intArray
___intArray[0] := 2007;
___...
___intArray[9] := 1973;

//sort
___QuickSort(intArray, Low(intArray), High(intArray)) ;

end;

Note: in practice, the QuickSort becomes very slow when the array passed to it is already close to being sorted.

No comments: