Topic 1 · Lesson 1 of 5
Algorithms, flow charts and sorting
Following an algorithm
An algorithm in words is a numbered list of steps. Some steps do a calculation, some test a condition and jump to another step ("if , go to Step 3"), and one step stops the algorithm and gives the output. To carry it out, keep a trace table: a column for each variable, and a new row each time a value changes. Do exactly what the step says, in order, even when you can see where it is heading.
A flow chart shows the same thing as a diagram. There are three shapes:
- rounded boxes for start and stop;
- rectangles for instructions ("Let ");
- diamonds for decisions, with two exits labelled Yes and No.
Follow the arrows. A loop is an arrow that leads back to an earlier box; the algorithm leaves the loop when a decision sends it along the other exit.
Exam questions on algorithms usually end with "state what the algorithm does". Look at your trace table and test the output against the inputs: an output of 91 from inputs 13 and 7 suggests multiplication; an output of 14 from 546 and 238 suggests the highest common factor.
Bubble sort
To sort into ascending order, compare the first two items and swap them if they are in the wrong order; then compare the second and third, and so on to the end of the list. That is one pass. After the first pass the largest item has "bubbled" to the end, so the next pass can stop one place earlier. Keep making passes until a pass makes no swaps.
Worked example
Bubble sort
Sort into ascending order.
Show solutionHide solution
- Pass 1: swap 7 and 3; 7 and 9 stay; swap 9 and 1; swap 9 and 5. List: (4 comparisons, 3 swaps).
- Pass 2: 3 and 7 stay; swap 7 and 1; swap 7 and 5. List: .
- Pass 3: swap 3 and 1. List: .
- Pass 4: no swaps, so the list is sorted.
With items, a bubble sort makes at most comparisons, and the same number of swaps in the worst case (a list in reverse order).
Quick sort
Quick sort splits the list around a pivot:
- Choose the middle item as the pivot. If a sublist has an even number of items, use the item to the right of the middle.
- Write the items smaller than the pivot (for ascending order) before it, in their original order, and the larger items after it. The pivot is now in its final place.
- Repeat with each sublist that has more than one item, choosing a new pivot in each.
- Stop when every item has been used as a pivot or is in a sublist of one.
Make each pivot clear (circle or bold it) and write the whole list after every pass.
Worked example
Quick sort
Sort into ascending order.
Show solutionHide solution
- Pass 1: pivot 31 (the 4th of 7 items). List: .
- Pass 2: pivots 25 (the 3rd of 4) and 36 (the 2nd of 2). List: .
- Pass 3: pivot 7 in . List: .
- Pass 4: pivot 12 in . List: . Sorted.
For descending order, put the larger items before the pivot.
Practise this topic
Both are part of Premium.