Overview

Sorting Algorithms

Implementation of Bubble Sort and Quick Sort.

Source Code

<?pas
// Sorting Algorithms: Implementation of Bubble Sort and Quick Sort.
// Utility to print an array
procedure PrintArray(const arr: array of Integer);
var
  i: Integer;
begin
  Print('[');
  for i := 0 to High(arr) do begin
    if i > 0 then Print(', ');
    Print(IntToStr(arr[i]));
  end;
  PrintLn(']');
end;

// --- Bubble Sort ---
// Simple but inefficient: O(n^2)
procedure BubbleSort(const data: array of Integer);
var
  i, j, temp: Integer;
  n: Integer;
begin
  n := Length(data);
  for i := 0 to n - 2 do
    for j := 0 to n - i - 2 do
      if data[j] > data[j + 1] then begin
        // Swap
        temp := data[j];
        data[j] := data[j + 1];
        data[j + 1] := temp;
      end;
end;

// --- Quick Sort ---
// Efficient divide and conquer: O(n log n)
procedure QuickSort_Internal(const data: array of Integer; L, R: Integer);
var
  i, j, pivot, temp: Integer;
begin
  i := L;
  j := R;
  pivot := data[(L + R) div 2];
  repeat
    while data[i] < pivot do Inc(i);
    while data[j] > pivot do Dec(j);
    if i <= j then begin
      temp := data[i];
      data[i] := data[j];
      data[j] := temp;
      Inc(i);
      Dec(j);
    end;
  until i > j;
  if L < j then QuickSort_Internal(data, L, j);
  if i < R then QuickSort_Internal(data, i, R);
end;

procedure QuickSort(const data: array of Integer);
begin
  if Length(data) > 0 then
    QuickSort_Internal(data, 0, High(data));
end;

// --- Main Execution ---

var data1 := [64, 34, 25, 12, 22, 11, 90];
var data2: array of Integer;

// Clone data for second test
data2.SetLength(Length(data1));
for var i := 0 to High(data1) do data2[i] := data1[i];

PrintLn('<h3>Bubble Sort</h3>');
Print('<b>Original: </b>');
PrintArray(data1);

BubbleSort(data1);

Print('<b>Sorted:   </b>');
PrintArray(data1);

PrintLn('<hr>');

PrintLn('<h3>Quick Sort</h3>');
Print('<b>Original: </b>');
PrintArray(data2);

QuickSort(data2);

Print('<b>Sorted:   </b>');
PrintArray(data2);
?>

Result

<h3>Bubble Sort</h3>
<b>Original: </b>[64, 34, 25, 12, 22, 11, 90]
<b>Sorted:   </b>[64, 34, 25, 12, 22, 11, 90]
<hr>
<h3>Quick Sort</h3>
<b>Original: </b>[64, 34, 25, 12, 22, 11, 90]
<b>Sorted:   </b>[11, 12, 22, 25, 34, 64, 90]
On this page