Sorting algorithms

EasyMediumHard
12345678910111213141516171819202122
Question 14
Easy

An aerospace engineer is writing an algorithm to sort drone altitudes in ascending order using a bubble sort.

Figure 1 shows the engineer's draft algorithm:

1  altitudes[0] ← 120
2  altitudes[1] ← 85
3  altitudes[2] ← 210
4  altitudes[3] ← 145
5  altitudes[4] ← 95
6  FOR p ← 0 TO 3
7      FOR q ← 0 TO 3
8          IF altitudes[q + 1] < altitudes[q] THEN
9              hold ← altitudes[q]
10             altitudes[q] ← altitudes[q + 1]
11             altitudes[q + 1] ← hold
12         ENDIF
13     ENDFOR
14 ENDFOR

In a previous draft of this algorithm, lines 6 and 7 were written as:

6      FOR p ← 0 TO 4
7      FOR q ← 0 TO 4

Explain why the algorithm would result in a runtime error if the value 4 was used instead of 3 on line 7.

[1]

Sorting algorithms Questions

  1. GCSE
  2. /Computer Science
  3. /Sorting algorithms