Reputation: 73
I have to find certain highest value in an array(for example fifth highest value).
I wrote an alogithm but it takes too long. Any ideas how to make it faster?
int tab[100];
// cin tab;
int position;
cin>>position;
// for example i need to find fifth highest
// value in an array.
int temp=0;
sort( tab, tab + 100, greater <int>() );
for(int y=0; y<100; ++y)
{
if (tab[y]==tab[y+1])
continue;
else
{
temp++;
if(temp==position)
cout<<tab[y];
}
}
Upvotes: 0
Views: 100
Reputation: 2851
As someone have mentioned in the comments using std:nth_element is a way to go if you don't want to write the algorithm yourself.
If you want to write it on your own you may want to look at this post:
Nth largest element in a binary search tree
It explains how to find the nth element in the binary search tree.
The information what the binary search tree is can be found on Wikipedia:
http://en.wikipedia.org/wiki/Binary_search_tree
This should give you a good starting point.
Upvotes: 1