Sorting algorithms

EasyMediumHard
12345678910111213141516171819202122
Question 2
Easy

A student is writing an algorithm to sort an array of integers in ascending order using a bubble sort.

Figure 1 shows the student's current algorithm:

1  nums[0] ← 15
2  nums[1] ← 8
3  nums[2] ← 22
4  nums[3] ← 4
5  FOR i ← 0 TO 2
6      FOR j ← 0 TO 2
7          IF nums[j + 1] < nums[j] THEN
8              temp ← nums[j]
9              nums[j] ← nums[j + 1]
10             nums[j + 1] ← temp
11         ENDIF
12     ENDFOR
13 ENDFOR

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

5      FOR i ← 0 TO 3
6          FOR j ← 0 TO 3

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

[1]

Sorting algorithms Questions

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