As noted, there are opportunities here to break this problem down. In order to bubble sort, you need to be able to swap. So let's make that a procedure.
Once we can make a swap, we need to make a pass over the array. As a mild optimization we'll pass an argument telling how deep into the array to sort. This because we know each pass will move the largest integer to the end of the array. And we'll return the number of swaps from the function.
Now that we can do this, we just need to make those passes in a loop, reducing the depth by one on each loop iteration.
program Sorting;
const
ArrSize = 5;
type
TArr = array [1..ArrSize] of integer;
var
sample : TArr = (45, 61, 3, 5, 23);
index : integer;
procedure swap(var arr : TArr; i, j : integer);
var
t : integer;
begin
t := arr[i];
arr[i] := arr[j];
arr[j] := t;
end;
function sortingpass(var arr : TArr; depth : integer) : integer;
var
i, n : integer;
begin
n := 0;
for i := 1 to depth - 1 do
begin
if arr[i] > arr[i + 1] then
begin
swap(arr, i, i + 1);
inc(n);
end;
end;
sortingpass := n;
end;
procedure bubblesort(var arr : TArr);
var
i : integer;
begin
for i := ArrSize downto 1 do
if sortingpass(arr, i) = 0 then
break;
end;
begin
bubblesort(sample);
for index := 1 to ArrSize do
writeln(sample[index]);
end.
Of course, we're not really using swap or sortingpass except as implementation details of bubblesort, so if we want to be a bit cleaner, we can define a unit which only exposes the bubblesort procedure.
And we'll use open arrays for greater flexibility.
unit Sort;
interface
procedure BubbleSort(var arr : array of integer);
implementation
procedure Swap(
var arr : array of integer;
i, j : integer
);
var
t : integer;
begin
t := arr[i];
arr[i] := arr[j];
arr[j] := t;
end;
function SortingPass(
var arr : array of integer;
depth : integer
) : integer;
var
i, n, s : integer;
begin
n := 0;
s := low(arr);
for i := s to s + depth - 1 do
begin
if arr[i] > arr[i + 1] then
begin
swap(arr, i, i + 1);
inc(n);
end;
end;
SortingPass := n;
end;
procedure BubbleSort(var arr : array of integer);
var
i, s, e, len : integer;
begin
s := low(arr);
e := high(arr);
len := e - s;
for i := len downto s do
if SortingPass(arr, i) = 0 then
break;
end;
end.
Now our test might simply be:
program Test;
uses
Sort;
var
sample : array of integer;
i : integer;
begin
setlength(sample, 5);
sample[0] := 4;
sample[1] := 1;
sample[2] := 67;
sample[3] := 21;
sample[4] := 19;
BubbleSort(sample);
for i := low(sample) to high(sample) do
writeln(sample[i]);
end.
With output:
1
4
19
21
67