Use 2 variables, namely small and smallest.
-
Iterate over each element of the given array.
-
Compare the element against
small. -
If it’s smaller than
small, compare it tosmallest. -
If it’s smaller than
smallest, assign the value ofsmallesttosmall, and the element tosmallest. -
Otherwise, assign the element to
small.
You still have to figure out how to initialise small and smallest in order to make the comparisons work as expected. Hint: limits!
Of course, this does not work for K > 2. If you don’t know K beforehand, you’ll need a container to store the results, and compare the elements against them. If you cannot use an extra container, good luck with that!
1
solved Finding K smallest integers in an unsorted array of size N [closed]