Implementing QuickSort Sorting Algorithm in Delphi

Trouble shooting tech is my specialty
Yuri_Arcurs / Getty Images

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 Algorithm

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 recursive "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] < Pivot 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 < iHi 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)) ;

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

There's a demo program that ships with Delphi, called "thrddemo" in the "Threads" folder which shows additional two sorting algorithms: Bubble sort and Selection Sort.

Format
mla apa chicago
Your Citation
Gajic, Zarko. "Implementing QuickSort Sorting Algorithm in Delphi." ThoughtCo, May. 18, 2017, thoughtco.com/implementing-quicksort-sorting-algorithm-in-delphi-1058220. Gajic, Zarko. (2017, May 18). Implementing QuickSort Sorting Algorithm in Delphi. Retrieved from https://www.thoughtco.com/implementing-quicksort-sorting-algorithm-in-delphi-1058220 Gajic, Zarko. "Implementing QuickSort Sorting Algorithm in Delphi." ThoughtCo. https://www.thoughtco.com/implementing-quicksort-sorting-algorithm-in-delphi-1058220 (accessed April 22, 2018).