Write a C program to find the n th largest or smallest number in a array without sorting.

It is very easy to find the largest number in the already sorted numbers. If the number is unsorted then we need to sort the array. After that we can easily find the n th largest number.

If we want to find the second largest number then we can get it by arr with n-1 th index. But here we have one twist.

We need to write the program to find the nth largest number without sorting the given array.

We strongly recommend you to try by yourself before scrolling down.

 

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int returnlarge(int arr[], int count, int large)
{
   int i;
   int nextlarge = INT_MIN;

   for(i = 0; i < count; i++)
   {
      if(arr[i] > nextlarge && (arr[i] < large))
         nextlarge = arr[i];
   }

   return nextlarge;
}

int main(int argc, char *argv[])
{   
   int i;
   int pos = 0;
   int *arr = NULL;
   int count = argc - 1;
   int large;
   arr = (int *)malloc(sizeof(int) * count);

   for(i = 0, argv++; i < count; i++)
   {
      arr[i] = atoi(argv[i]);
      printf("arr[i] = %d\n",arr[i]);
   }

   for(;;)
   {
      printf("Enter the possition of largest number : ");
      scanf("%d", &pos);

      if(pos <= 0 || pos > count) break;
      large = INT_MAX;

      for(i = 0; i < pos; i++)
         large = returnlarge(arr, count, large);

      printf("%d largest number is : %d\n", pos, large);
   }

   free(arr);
   return 0;
}

Compile: gcc filename.c [or] g++ filename.cpp

Output:

./a.out 1 85 95 15 48 96 2
Enter the possition of larget number : 
1
1 largest number is  :96
Enter the possition of larget number : 
2
2 largest number is  :95
Enter the possition of larget number : 
3
3 largest number is  :85
Enter the possition of larget number : 
4
4 largest number is  :48
Enter the possition of larget number : 
5
5 largest number is  :15
Enter the possition of larget number : 
6
6 largest number is  :2
Enter the possition of larget number : 
7
7 largest number is  :1
Enter the possition of larget number : 
0

 

Now try to write a program to find the Nth smallest number.

Also if you find any error or alternate simple method let us know in the comments.