# Thread: How to find the smallest 5 numbers in an array?

1. ## How to find the smallest 5 numbers in an array?

I can find the smallest number in an array:

Code:
```#include <stdio.h>

int main(){
int array[10] = {22,14,3,6,2,37,19,24,9,12};

int i;
int smallest = array[0];

for(i = 0; i < 10; i++){

if(array[i] < smallest){
smallest = array[i];
}
}
printf("%d ", smallest);

}```
...but how can I get the smallest 5 numbers in an array? I'm struggling with this. Any help? Thanks.

2. Sort the array in ascending order; then first N elements of it will be the N smallest numbers in the array.

3. You could sort the array to begin with, then the 5 smallest numbers would be the first 5 elements of the array.

4. No need to sort the entire arry for this.

You can try like this. Do 5 iterations, in each iteration bring the smallest to the front. I mean start first iteration so that smallest comes to a[0], then start 2nd iteration from a[1] so that 2nd smallest comes to a[1]. Do this for 5 times. You'll endup with 5 small integers in the first five elements of array.

5. Originally Posted by sana.iitkgp
Do 5 iterations, in each iteration bring the smallest to the front. I mean start first iteration so that smallest comes to a[0], then start 2nd iteration from a[1] so that 2nd smallest comes to a[1]. Do this for 5 times. You'll endup with 5 small integers in the first five elements of array.
In other words, do a partial sort using selection sort. In this case, I think that this is the best approach. If the array was much larger, and n possibly much larger than 5, then the approach that does quicksort-style partitioning, with recursion on the partition that contains the nth element, is likely to be better if order is not important.

Popular pages Recent additions