129k views
4 votes
Given the following sorting algorithm:

01 public static void selectionSort(int [ ] numbers) {
02 int i, j, temp;
03 int indexSmallest;
04
05 for (i = 0; i < numbers.length - 1; i++) {
06
07 // Find index of smallest remaining element
08 indexSmallest = i;
09 for (j = i + 1; j < numbers.length; j++) {
10
11 if (numbers[ j ] < numbers[ indexSmallest ]) {
12 indexSmallest = j;
13 }
14 }
15
16 // Swap numbers[ i ] and numbers[ indexSmallest ]
17 temp = numbers[ i ];
18 numbers[ i ] = numbers[ indexSmallest ];
19 numbers[ indexSmallest ] = temp;
20 }
21 }
and applying it to the following list:

int[ ] numbers = {89, 46, 59, 7, 19, 66};
What value will be at index 0 in numbers after line# 19 executes 5 time(s)?

User Booga Roo
by
8.6k points

1 Answer

4 votes

Final answer:

After 5 iterations of the selection sort algorithm, the array will have the smallest 5 elements in order, and the first element will remain unchanged from the first iteration. The value at index 0 after line #19 executes 5 times is 7.

Step-by-step explanation:

The given selection sort algorithm works by repeatedly finding the smallest element from the unsorted portion of the array and moving it to the beginning. After line #19 executes for the 5th time, it means we would have completed 5 iterations of the outer for-loop (lines 05-20), effectively placing the 5 smallest elements of the array in the first five positions, in sorted order.

Let's follow the sorting process for the array numbers = {89, 46, 59, 7, 19, 66} for 5 iterations:

  1. First iteration, the smallest number 7 is found and swapped with itself (as it is already in the first position after swapping with the number at index 0). Array becomes {7, 46, 59, 89, 19, 66}.
  2. Second iteration, the next smallest number 19 is found and swapped with the number at index 1. Array becomes {7, 19, 59, 89, 46, 66}.
  3. Third iteration, 46 is the next smallest and is swapped with the number at index 2. Array becomes {7, 19, 46, 89, 59, 66}.
  4. Fourth iteration, 59 is found and swapped with the number at index 3. Array becomes {7, 19, 46, 59, 89, 66}.
  5. The fifth iteration, 66 is located and swapped with the number at index 4. Array becomes {7, 19, 46, 59, 66, 89}.

After the 5th iteration, the value at index 0 in numbers has not changed since the first iteration. Therefore, the value at index 0 after line #19 executes 5 times is 7.

User Azkotoki
by
8.7k points