Y13 Unit 0 - Class Structure
Y13 Unit 1 - Searching Algorithms
Y13 Unit 2 - Abstract Data Structures (HL)
Y13 Unit 3 - Computer Organization (Binary)
Y13 Unit 4 - Computer Organization (Architecture)
Y13 Unit 5 - Resource Management (HL)
Y13 Unit 6 - Control (HL)
Paper 3
1 of 2

Selection Sort

The selection sort that you need to know for the exam starts at index 0 and looks through the entire array keeping track of the the index of the smallest value in the array and then swaps the value at the smallest index with the value at index 0. Then it does the same thing for index 1, then 2, and so on until it reaches the length of the array minus one. At this point the array is sorted in ascending order.

You can see a visualization here: https://visualgo.net/en/sorting

To identify a selection sort look for the following:

  • a nested for loop with the outer loop starting at 0 and ending when the index reaches length – 1 (see line 7 below)
  • the index of the smallest value should start at the outer loop index (see line 9 below)
  • the inner loop should start at the outer loop index + 1 and loop through the whole array (see line 10 below)
  • if the value in the array at the index of the inner loop is less than the value at the smallest index then set the smallest index to the index of the inner loop (see lines 12 – 15)
  • swap the value at the outer loop index and the smallest value (the one at the smallest value index) (see lines 17-19)

In other words,

  1. Loop through the entire array to find the smallest element
  2. When found, swap it with the first element of the array
  3. Search for the next smallest element and swap it with the second element of the array
  4. Search for the next smallest element and swap it with the third element of the array
  5. repeat this process with the remaining items in the array