13.4. 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.

Here is a folk dance video that shows the selection sort process.

To identify a selection sort look for the following:

The code for selectionSort below is from the AP CS A course description.

To see this executing using the Java Visualizer click on the following SelectionSort

    12-4-1: Under what condition will a selection sort execute faster?
  • If the data is already sorted in ascending order
  • How would this be faster? Look at the code.
  • If the data is already sorted in descending order
  • How would this be faster? Look at the code.
  • It will always take the same amount of time to execute
  • A selection sort always does the same number of comparisons and always takes the same time to execute regardless of the order of the data.

    12-4-2: This method should sort the numbers in the passed array into ascending order. But, it does not work. Which of the following lines is wrong?

    public static void selectionSort(int[] elements)
    {
      for (int j = 0; j < elements.length − 1; j++)      // line 1
      {
         int minIndex = j;                               // line 2
         for (int k = 0; k < elements.length; k++)       // line 3
         {
            if (elements[k] < elements[minIndex])        // line 4
            {
               minIndex = k;                             // line 5
            }
         }
         int temp = elements[j];
         elements[j] = elements[minIndex];
         elements[minIndex] = temp;
       }
    }
    
  • line 1
  • The outer loop starts at 0 and ends when it reaches the length - 1.
  • line 2
  • The min index should be set to the outer loop index before the start of the inner loop.
  • line 3
  • The inner loop should start at the outer loop index + 1.
  • line 4
  • You should compare the element at the inner loop index to the element at the min index to see if it is smaller.
  • line 5
  • You should save the new min index as the inner loop index.

You can step through the code above by clicking on the following Ex-12-4-2.

Next Section - 13.5. Insertion Sort