Print n smallest elements from given array in their original order

Given with array of let’s say k elements the program must find the n smallest elements amongst them in their appearing order.

Input : arr[] = {1, 2, 4, 3, 6, 7, 8}, k=3
Ouput : 1, 2, 3
Input k is 3 it means 3 shortest elements among the set needs to be displayed in original order like 1 than 2 and than 3

Algorithm

START
Step 1 -> start variables as int i, max, pos, j, k=4 and size for array size
Step 2 -> Loop For i=k and i=0 and j--
      If arr[j]>max
         Set max = arr[j]
         Set pos = j
      End
   End
   IF max> arr[i]
      Set j = pos
      Loop While j  Loop For i = 0 and i 

Example

#include 
int main() {
   int arr[] = {5,8,3,1,2,9};
   int i, max, pos, j, k=4;
   int size = sizeof(arr)/sizeof(arr[0]);
   //Using insertion sort, Starting from k.
   for(i=k;i=0;j--) {
         if(arr[j]>max) {
            max = arr[j];
            pos = j;
         }
      }
      if ( max> arr[i] ) {
         j = pos;
         while( j 

Output

if we run above program then it will generate following output.

5 3 1 2
Updated on: 2019-07-30T22:30:26+05:30

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements