Quicksort Demonstration 1a (Lazarus)

program QuickSortDemo1a;
  {$APPTYPE CONSOLE}
uses
  SysUtils, crt;
const
  UPPER_BOUND = 10;
  FIELD_WIDTH = 3;
var
  Ints : array[1..UPPER_BOUND] of integer = (10, 7, 3, 5, 8, 2, 6, 9, 1, 4);

procedure Quicksort(Left, Right: integer);
var
  ptrLeft, ptrRight, Pivot, Temp: integer;

procedure DisplayArray;
var
  Count : integer;
begin
  for Count := 1 to UPPER_BOUND do
    begin
      if (Count >= Left) and (Count <= Right) then
        textBackground(yellow)
      else
        textBackground(black);
      if Count = ptrLeft  then
        textColor(green)
      else if Count =  ptrRight then
        textColor(Red)
      else
        TextColor(white);
      if Ints[Count] =  Pivot then
        textBackground(lightgray);
      write(ints[Count] : FIELD_WIDTH);
    end;
    textColor(white);
    textBackground(black);
    if PtrLeft = PtrRight then
      writeln('  Pointers coincide. Press return to continue.')
    else
      writeln('                     Press return to continue.');
    readln;
end;
begin
  ptrLeft := Left;
  ptrRight := Right;
  Pivot := Ints[(Left + Right) div 2];
  textColor(white);
  writeln('Quicksort for index ', Left,  ' to ', Right, ' with pivot ', Pivot,':');
  DisplayArray;
  repeat
    {Increment left pointer while  it has not reached upper
     index of array segment and value remains less than pivot.}
    while (ptrLeft < Right) and (Ints[ptrLeft] < Pivot) do
      begin
        writeln('Left pointer moves right:');
        inc(ptrLeft);
        DisplayArray;
      end;
    {Decrement left pointer while it has not reached lower
     index of array segment and value remains greater than pivot.}
    while (ptrRight > Left) and (Ints[ptrRight] > Pivot) do
      begin
        writeln('Right pointer moves left:');
        dec(ptrRight);
        DisplayArray;
      end;
    if ptrLeft <= ptrRight then  //if left pointer and right pointer have not crossed
      begin
        //Swap values at left and right pointers if pointers are not equal
        if ptrLeft < ptrRight then
          begin
            writeln('Swapping ', Ints[ptrLeft], ' with ', Ints[ptrRight]);
            Temp := Ints[ptrLeft];
            Ints[ptrLeft] := Ints[ptrRight];
            Ints[ptrRight] := Temp;
            DisplayArray;
          end;
        writeln('Both pointers move one place:');
        //Left pointer moves right and right pointer moves left.
        inc(ptrLeft);
        dec(ptrRight);
        DisplayArray;
      end;
  until ptrLeft > ptrRight;  //Until pointers have crossed
  write('Pointers have crossed. ');
  //Sort the left partition if necessary.
  if ptrRight > Left then
    Quicksort(Left, ptrRight);
  //Sort the right partition if necessary.
  if ptrLeft < Right then
    Quicksort(ptrLeft, Right);
end;
begin
  Quicksort(1, UPPER_BOUND);
  writeln('Sorted!');
  readln;
end.
Programming - a skill for life!

Discussion of quicksort