[Solved] Finding K smallest integers in an unsorted array of size N [closed]


Use 2 variables, namely small and smallest.

  1. Iterate over each element of the given array.

  2. Compare the element against small.

  3. If it’s smaller than small, compare it to smallest.

  4. If it’s smaller than smallest, assign the value of smallest to small, and the element to smallest.

  5. 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]