So basically, I have an array of ints, and I need to find the index of the third highest int. How do I do it efficiently and quickly, without sorting the ENTIRE array, or going through the tedious loops of finding the highest number everytime, then setting that to 0, and repeating, till I find the third highest number. Or I could have a loop which iterates through each element, checks if it is higher than a variable for the 1st, 2nd or 3rd highest ints, and if it is, replacing the respective variable with the new int.
However, these are all messed up methods where I could easily make a small mistake in the algorithm. I was searching around and saw some references that indicated that there might be a built-in function in C++, to find the nth highest element, something like std::nth_element. However, it's not showing up on Visual C++'s (I know, I know, its made by MS, but then the autosuggestions and auto-indenting and stuff are really helpful for a beginner) autosuggest, and I'm not sure what syntax to use. Can someone tell me if theres some function in the standard header files that can do this job for me? And also, a little pointer about the syntax for that function would be real nice...
and um...the array i need to sort is in dynamic memory, whose size is set while the program is running, based on user input.
I don't think the rest of my code would really help, but here it is anyways...:
// bccs.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void main(){
int cand, voters;
int * candvots = NULL;
//input number of candidates, voters. Create an array of size cand-1, initialize all values to 0
cin >> cand >> voters;
candvots = new int[cand];
for(int i=0; i<cand; i++){
candvots[i]=0;
}
//loop through number of voters, for each vote, increase candvots[select] by 1
int select; //which candidate each voter votes for
for(; voters>0; voters--){
cin >> select;
candvots[select]++;
}
//loop thrice. Find highest value, delete, repeat. store third higest value to 'select'
std::n
//output select
while(vot > 0){
int candvotedfor;
cin >> candvotedfor;
candvots[candvotedfor - 1] ++;
vot--;
}
int third = 0;
int sortit = 0;
int maxvotes = 0;
int maxcand = 0;
while(third < 3){
while(sortit < cand){
if (candvots[sortit] > maxvotes){
maxvotes = candvots[sortit];
maxcand = sortit;
sortit--;
}
}
candvots[maxcand]= 0;
third++;
}
cout << maxvotes;
/*while(cand > 0){
cout << "\n Candidate No: " << cand << " votes = " << candvots[cand - 1];
cand --;
}*/
system("pause");
}
of course this code still has relics of my old sorting code which I realise has some flaws in it...

New Topic/Question
Reply




MultiQuote





|