# Quicksort Demonstration 1b (Lazarus or Delphi)

This demonstration implements the same quicksort algorithm as 1a but omits the colour coding.

```program QuickSortDemo1b;
{\$APPTYPE CONSOLE}
uses
SysUtils;
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 DisplayArray;
var
Count : integer;
begin
for Count := 1 to UPPER_BOUND do
write(ints[Count] : FIELD_WIDTH);
writeln;
end;

procedure Quicksort(Left, Right: integer);
var
ptrLeft, ptrRight, Pivot, Temp: integer;
begin
//writeln('Quicksort procedure for index ', Left,  ' to ', Right);
ptrLeft := Left;
ptrRight := Right;
Pivot := Ints[(Left + Right) div 2];
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
inc(ptrLeft);
{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
dec(ptrRight);

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;
//Move pointers one place (left pointer moves right and right pointer moves left).
inc(ptrLeft);
dec(ptrRight);
end;
until ptrLeft > ptrRight;  //Until pointers have crossed
//Sort the left segment of the partition if there is more than one item in it.
if ptrRight > Left then
Quicksort(Left, ptrRight);
//Sort the right segment of the partition if there is more than one item in it.
if ptrLeft < Right then
Quicksort(ptrLeft, Right);
end;
begin
writeln('Array to be sorted:');
DisplayArray;
Quicksort(1, UPPER_BOUND);
writeln('Sorted array:');
DisplayArray;
end.```

In the next demonstration the pivot is the first item in the list.

Programming - a skill for life!

Discussion of quicksort