Sorting

Selection Sort

🙋 Need help? Ask an expert now!

In Java, "selection sort" is a partnership of searching and sorting. We can agree that data is much easier to process and handle if it is sorted, so let's see how this sort method works.

SelectionSortExample.java
package exlcode;

public class SelectionSortExample {

  public static void main(String[] args) {
    int[] exampleVariableOne = {17, 5, 21, 8, 19, 2, 23, 15, 4, 13};
    selectionSort(exampleVariableOne);
    System.out.println("Sorted Values: ");
    for (int val : exampleVariableOne) {
      System.out.print(val + " ");
    }
  }

  public static void selectionSort(int[] parameterOne) {
    for (int i = 0; i < parameterOne.length - 1; i++) {
      int min = i;
      for (int j = i + 1; j < parameterOne.length; j++) {
        if (parameterOne[j] < parameterOne[min]) {
          min = j;
        }
      }
      // finds the smallest value in the array and swaps it with
      // the value at index 0
      // the process continues until the array is sorted
      int temp = parameterOne[i];
      parameterOne[i] = parameterOne[min];
      parameterOne[min] = temp;
    }
  }
}

There are two loops in a selection sort. The inner loop finds the next smallest or largest value while the outer loop places that value into its proper location. Although selection sort is one of the easier sorts to code, it is also fairly inefficient as there is no way you can end the sort early, even if the list is already sorted. No matter what the state of the list is, the selection sort will go through each index, starting with zero, and sort each element through to the end.

Application Question

Consider the following selection sort method:

public void selectionSort(int[] paramOne){
              for (int j = 0; j &amp;#60; paramOne.length-1; j++){
                int m = j;
                for (int k = j + 1; k &amp;#60; paramOne.length; k++){
                  if (paramOne[k] &amp;#60; paramOne[m]){
                    m = k;
                  }
                }
                int temp = paramOne[m];  
                paramOne[m] = paramOne[j];
                paramOne[j] = temp;
                /* End of outer loop */
              }
            }
            

Assume that selectionSort is called with the array {6, 3, 2, 5, 4, 1}. What will the value of paramOne be after three passes of the outer loop (i.e., when j = 2 at the point indicated by /* End of outer loop */)?