Grade 11 · One-dimensional arrays · Lesson and coding task · about 16 minutes
Open this task in the Delphi workspace →
The bubble sort is the CAPS sorting algorithm. Repeatedly compare neighbours and swap them when they are in the wrong order — the biggest values "bubble" to their places:
for i := 1 to 4 do // passes
for j := 1 to 5 - i do // neighbours left to check
if arrMarks[j] < arrMarks[j + 1] then // wrong order?
begin
iTemp := arrMarks[j]; // the three-line swap
arrMarks[j] := arrMarks[j + 1];
arrMarks[j + 1] := iTemp;
end;
With < in the comparison this sorts descending (highest first); > sorts ascending. When data lives in parallel arrays, you must swap the name every time you swap the mark — or the wrong learner walks off with the trophy.
This exercise's starter fills form-level arrays in FormCreate (it runs automatically when the form loads) — sort those.
What you will do
- Bubble-sort the marks in DESCENDING order
- Swap the names whenever you swap the marks (parallel arrays!)
- Display the sorted list: Anele: 90 first, Sipho: 33 last
Hints
- Descending means: swap when arrMarks[j] < arrMarks[j + 1].
- Inside the IF you swap twice: marks with iTemp, names with sTemp.
- After sorting, one more FOR loop displays the list.
Model solution
var
arrNames : array[1..5] of String;
arrMarks : array[1..5] of Integer;
procedure TfrmSort.FormCreate(Sender: TObject);
begin
arrNames[1] := 'Thabo'; arrMarks[1] := 78;
arrNames[2] := 'Lerato'; arrMarks[2] := 45;
arrNames[3] := 'Anele'; arrMarks[3] := 90;
arrNames[4] := 'Sipho'; arrMarks[4] := 33;
arrNames[5] := 'Zanele'; arrMarks[5] := 67;
end;
procedure TfrmSort.btnSortClick(Sender: TObject);
var
i, j, iTemp : Integer;
sTemp : String;
begin
for i := 1 to 4 do
for j := 1 to 5 - i do
if arrMarks[j] < arrMarks[j + 1] then
begin
iTemp := arrMarks[j];
arrMarks[j] := arrMarks[j + 1];
arrMarks[j + 1] := iTemp;
sTemp := arrNames[j];
arrNames[j] := arrNames[j + 1];
arrNames[j + 1] := sTemp;
end;
for i := 1 to 5 do
memOutput.Lines.Add(arrNames[i] + ': ' + IntToStr(arrMarks[i]));
end;