Friday, October 10, 2008

Nth biggest number



#include <iostream>
#include <algorithm>

using namespace std;
void printVec(int a)
{
cout << a << endl;
}

int biggest(int a[], int num)
{
int i, j, k;
int big;
int oldbigindex, bigindex;
bigindex = -1;
for(k = 0; k < num; k++)
{
big = -100000;
for(i = 0; i < 10; i++)
{
if(k)
{
if(a[i] >= big && a[i] <= a[oldbigindex])
{

if(a[i] == a[oldbigindex] && i >= oldbigindex) continue;
big = a[i];
bigindex = i;
}
}
else if(a[i] >= big)
{
big = a[i];
bigindex = i;
}
}
oldbigindex = bigindex;
}
return(big);
}



int main()
{
int arr[10] = { 9, 10, 15, 4, 9, 7, 9, 6, 11, 4 };
for_each(arr, arr+10, printVec);
cout << "Third Big: " << biggest(arr, 3) << endl;
cout << "Fourth Big: " << biggest(arr, 4) << endl;
cout << "Fifth Big: " << biggest(arr, 5) << endl;
cout << "Sixth Big: " << biggest(arr, 6) << endl;
cout << "Seventh Big: " << biggest(arr, 7) << endl;
}

1 comment:

Unknown said...

Hi,

Its a really good algorithm.
Question:
Have you tried replacing
if(a[i] == a[oldbigindex] && i >= oldbigindex) continue;

with

if(a[i] == a[oldbigindex] || i == oldbigindex) continue;


It worked for me for some cases I tested it with.

I coulnd't get why i >= oldindex is used ??

this case failed for me to find correct value in case there was a duplicate. (probably that was because I changed && with ||.

would like to hear from you.

Thanks
Vikas