Sorting algorithms

EasyMediumHard
12345678910111213141516171819202122
Question 13
Easy

An engineer is writing a bubble sort algorithm to arrange the weights of 6 cargo crates in ascending order. The weights (in kg) are stored in a 0-indexed array weights of size 6:

1  weights[0] ← 120.5
2  weights[1] ← 85.2
3  weights[2] ← 210.0
4  weights[3] ← 145.8
5  weights[4] ← 95.1
6  weights[5] ← 175.3
7  FOR pass_idx ← 0 TO 4
8      FOR compare_idx ← 0 TO 4
9          IF weights[compare_idx + 1] < weights[compare_idx] THEN
10             temp ← weights[compare_idx]
11             weights[compare_idx] ← weights[compare_idx + 1]
12             weights[compare_idx + 1] ← temp
13         ENDIF
14     ENDFOR
15 ENDFOR

In a previous version of this algorithm, line 8 was written as:

FOR compare_idx ← 0 TO 5

Explain why this change causes an error when the algorithm is executed.

[1]

Sorting algorithms Questions

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