Reputation: 67
#include <iostream>
#include <cstdlib>
#include <ctime>
#include<algorithm>
using namespace std;
bool findNthMax(double arr[], int len, int n, double& nth_max)
{
sort(arr, arr+n);
//Counter
int c = 1;
//Initialize nth max
nth_max = arr[0];
//Loop in the array while the count is less than (n)
for (int i = 0; i < len && c < n; i++)
{
if (arr[i] != nth_max)
c++;
nth_max = arr[i];
}
return nth_max;
}
int main()
{
int n;
double arr[10];
double y;
cout << "The random array elements are:" << endl;
srand((unsigned)time(0));
for(int i=0; i<10; i++){
arr[i] = (rand()%100);
cout << arr[i] << ' ' ;
}
cout << endl;
cout << "Input a positive integer n: " ;
cin >> n ;
if(n>10)
cout << "The nth largest value does not exist." << endl;
else
cout << "The nth largest value is: " << findNthMax(arr, 10, n, y) << endl;
return 0;
}
EDIT: the function returns false if the nth largest value does not exist; the first parameter is the input array; the second parameter is the array size; the third parameter is used to pass the value of n to the function; the last parameter is nth largest value being found.
The main function generates an array with 10 double random elements (in the range [0, 99]. It prints out those 10 elements. Prompt a user to enter a positive integer n, then print out the nth largest value in the array.
How ever my outputs shows that nth largest: 1 when n = 2
Upvotes: 0
Views: 1459
Reputation: 592
You're incrementing c
to 2 after if arr[1] != nth_max
. This means that c !< n
, so you're for
loop exits after 2 loops through.
You need to sort the entire array, b/c you're missing the case where you could have 8 duplicates before the 2nd max, for instance { 8, 8, 8, 8, 8, 8, 8, 8, 1, 2, 8, 8, 8 }.
sort(arr, arr+len);
You should start your for
loop at the end of the array...
nth_max = arr[len-1];
for (int i = len-1; i >= 0 && c < n; i--)
Then also run the function before outputting the variable y
:
findNthMax(arr, 10, n, y);
cout << "The nth largest value is: " << y << endl;
Upvotes: 1