Search code examples
algorithmsortingselection-sort

Selection sort order


My book says:

Suppose you have a group of N numbers and would like to determine the kth largest. This is known as the selection problem. Most students who have had a programming course or two would have no difficulty writing a program to solve this problem. There are quite a few “obvious” solutions. One way to solve this problem would be to read the N numbers into an array, sort the array in decreasing order.

It says that it would make sense to sort the array in decreasing order. How does that make sense? If I have an array of {1,9,3,7,4,6} and I want the greatest element, I would sort it in an increasing order so {1,3,4,6,7,9} and then return the last element. Why would the book say in decreasing order?


Solution

  • Because you may not want the largest element, the book says

    would like to determine the kth largest

    If you sort it in ascending order, how do you know what the, say, 3rd largest number is without first finding out how big the array is?

    This would be easier if the array was descending, as the 3rd largest will simply be the 3rd element.