It's entirely possible that you are using a small test data set that produces success, but doesn't have scenarios where your code would fail. The lesson here is to develop test data that fully exercises code, including all the corner cases.
Frankly, I don't understand the logic behind that code at all. It compares the number of votes to the index of the candidate??? Why????
Also, nested for loops??? Not needed and doesn't work. But, if you insist on it, the comparison needs to be between candidate[i] and candidate[j], not i and candidate[j].
This can be done in one pass through the array to find the lowest vote count(s), followed by another for loop to eliminate the losers. The pseudocode is simple.
- Create a var to hold the minimum number of votes
- Store the first candidate's vote count in that var.
- compare the stored value to the next candidate. If the next candidate has lower votes, update the var from step 1.
- repeat for the rest of the candidates.
- Now, go back through the list with a second loop (not nested) and mark anyone with that vote count as eliminated.
Nested loops are not always the answer.
Finally, be careful about the placement of a return statement. In this case, as soon as a candidate is eliminated, the return will execute. What if there's a candidate with a lower count later on? Or, what happens when there are so many voters that every candidate gets more votes than the total number of candidates (greater than the max values of i and j)?
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)