Question: In this exercise the goal is to implement the Selection Sort algorithm in full. The skeleton contains three methods: A main method which will allow
In this exercise the goal is to implement the Selection Sort algorithm in full.
The skeleton contains three methods:
-
A main method which will allow you to do your own testing, and give a working example.
-
A selectionSort method where you'll do the actual implementation of the sorting algorithm.
-
A printArray method to help with print the data, don't change it.
The selectionSort method takes in an int[] called data. This is the array that you are to sort. The array may be of any size. At the end of the method you should return data;. This line has already been added, so you can just leave it as is.
For the tests to ensure you are correctly implementing a Selection Sort (and not some other sort, or using a library), you must print out the array using printArray(data) every time you swap elements in the array. You should not print it out any other time in the selectionSort method. For consistency in which version of Selection Sort is implemented:
-
Stop the sort once the unsorted area is only one element.
-
Don't swap if the minimum element is the first element in the unsorted area (so no print out in this case).
import java.util.Arrays;
public class SelectionSort {
//Don't touch this method! private static void printArray(int[] a) { System.out.println(Arrays.toString(a)); }
//Complete this method. public static int[] selectionSort(int[] data) {
//Implement a Selection Sort on data here!
return data; }
//You can mess around in the main method //as you wish. As long as it compiles, //it won't affect the testing. public static void main(String[] args) {
int[] testData = {45, 23, 66, 12, 87, 19};
System.out.println("Sorting."); testData = selectionSort(testData); System.out.println("After sorting the array is: "); printArray(testData); }
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
