Picking the initial five numbers does not require you to pick the five smallest numbers before looking at the rest of the array: if you did, you wouldn't need to look through the rest of the array.
Let's simplify this by writing a signature for your method:
getSmallest(array<int> input, int nSmallest) -> array<int> # length of nSmallest
What does this method have to do?
- Put the first
nSmallest
elements into the output array
- For each additional element, check to see if it is smaller than any element in the output array.
- If so, swap it with that element in the output array.
- If an element is swapped, repeat for the swapped-out element (to ensure that it is not smaller than any of the remaining elements)
The resulting output array will hold all the elements which are smallest, and nothing will have been sorted. Let's write some pseudocode, starting with the check against the output array:
# returns true if the candidate was swapped in, false otherwise.
# NOTE: outputArray and candidate can be modified by this function!
# If boolean is 'true' then 'candidate' will contain the swapped out element
swapElement(array<int> outputArray, int candidate) -> boolean
foreach idx->smallNumber in outputArray
if (candidate < smallNumber) {
outputArray[idx] = candidate
candidate = smallNumber
return true
}
return false
Now that we've handled this core problem, how do we use the solution?
getSmallest(array<int> input, int nSmallest) -> array<int>
output[nSmallest] = copy(input, nSmallest) # copies the first nSmallest elements into output
# Iterate through the remainder of the list
for (idx = nSmallest, length(input), idx++) {
checkingCandidate = true
candidate = input[idx]
while (checkingCandidate){ # This ensures that swapped candidates get checked too, no matter how many
checkingCandidate = swapElement(output, candidate)
} # This will quit once we are no longer swapping elements.
}
return output
And there you have your complete solution - in pseudocode. As you can see, the core problem is having your output array, and swapping in the smaller element as you find it (preventing you from needing to sort the array first). Once you reduce the problem to 'is x element smaller than anything in y array', the rest is just iteration. Oh, and at the end you just add all the numbers in your output array - which should be trivial.