jump to navigation

Find Nth Largest number in an Array August 12, 2008

Posted by Thinker in General.
trackback

The below is my implementation of finding the nth largest(whichmax)number in the given array of integers.

This would work for both positive and negative integers. This also  affects the given array by manipulating the values of the source array. Hence if you want an non-manipulative algo, this is NOT the one.

 

#include “stdafx.h”

class Program

{

public:    

int GetNthLargestOptimized(int **intArray,int Length, int whichMax);

};

int Program::GetNthLargestOptimized(int **intArray,int Length, int whichMax)

{

int MaxIndex =0;

int MinIndex =0;

bool minFound = false;

for(int nth=0;nth<whichMax;nth++)

      {

for(int index=0;index<Length;index++)

            {

if((*intArray)[MaxIndex]< (*intArray)[index])

                  {    

                        MaxIndex = index;

                  }

if(!minFound && (*intArray)[MinIndex] > (*intArray)[index])

                  {

                        MinIndex = index;

                  }

            }

if(!minFound)

            {

                  minFound = true;

            }

if(   nth != whichMax -1)

            {

                  (*intArray)[MaxIndex]= (*intArray)[MinIndex];

            }

      }

return (*intArray)[MaxIndex];

}

int _tmain(int argc, _TCHAR* argv[])

{

      Program m;

int intNegativeArray[10]={-1,-2,-3,-4,-5,-6,-7,-8,-9,-10};

int intArray[10]={23,345,345,12,45,23,34,4,6,555};

int *intNegativePtr = intNegativeArray;

      printf(“4th Largest in Negative array:%d\n”,m.GetNthLargestOptimized(&intNegativePtr,10,4));

int *intPtr = intArray;

      printf(“4th Largest in Positive array:%d\n”,m.GetNthLargestOptimized(&intPtr,10,4));

return 0;

}

Comments»

1. Sriram - October 15, 2008

Hi,

I tried your program its working good.

I have written a similar one, at the same time it takes care of not modifying the actualy array, it doesnt sort and also takes care of duplicates.

http://sriramkondaviews.blogspot.com/2008/10/nth-biggest-number.html

Please comment.