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;

}

## 1 comment:

i think your program will not run in O(n) time , it runs in O(kn) where k is kth largest or smallest element

Post a Comment