Great job! You have finished the selection sort algorithm. Let’s take a final look at what you did.
We found the smallest element in our array and then swapped it with the first element in our array, if the first element wasn’t already the smallest value. Next, we found the second smallest element, and swapped it with the second element in the list. This process keeps going till we are looking at the last item in the array, and there’s no sorting left to do.
This is where selection sort gets its name from: one item at a time we are selecting the smallest item, and moving it to it’s “sorted” position.
While selection sort is a fine algorithm to use on small arrays it doesn’t perform well on larger data sets as ours is built with a nested
for loop. This is generally a sign of quadratic complexity and in the case of selection sort we find that best, worst and average case are an
Here we have our finished code from the last exercise. Go ahead and run the code again to see the results!
Try changing the data provided to the input array,
data. What happens when you provide just one or no values?
Does your selection sort algorithm run on an array of string values? You’ll have to change some variable types to make this work — right now, all of our methods are expecting
ints, but we’d want
Strings. Also, comparison operators like
> don’t work with Strings. Instead, take a look at the compareTo() documentation to see how to compare Strings.
Want another challenge?
Imagine that you have been given the instructions to change selection sort to order the elements in descending, rather than ascending order? Can you do it?
If you need a hint, take a look at the
if statement within the
selectionSort() function. Also, while it is not required to accomplish this task, you might want to rename
currentMaximumIndex for human readability!