LearnStanmorephysics

Grade 11 · Powering Up

Bubble sort

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.

Exam tip. The three-line swap with a temp variable is a guaranteed mark. Write it the same way every time until you can do it asleep.

What you will do

Hints
  1. Descending means: swap when arrMarks[j] < arrMarks[j + 1].
  2. Inside the IF you swap twice: marks with iTemp, names with sTemp.
  3. 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;

About this material

This platform provides original CAPS-aligned practice material and study tools. Content is machine-verified and has not been reviewed by subject specialists. It is not affiliated with or endorsed by the Department of Basic Education. Learners should also use official past papers and consult their teachers where uncertain.