Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment

Back to Classroom

Selection Sort

Java Search Sort Course

Engineers From These Top Companies and Universities Trust EXLskills

1M+ Professionals | 100+ Institutions

This is the EXLskills free and open-source Java Search Sort Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java searching and sorting.

Is this course FREE?

Yes, this a 100% free course that you can contribute to on GitHub here!

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.

publicvoidselectionSort(int[] paramOne){
for (int j = 0; j < paramOne.length-1; j++){int m = j;
for (int k = j + 1; k < paramOne.length; k++){if (paramOne[k] < 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 */)?