0

To figure out the winner, I am trying to do a bubble sort and then print the last name (or names if the last two are tied). For some reason, after it goes through the first run-through of the bubble sort (correctly, with the "for" loop below), it forgets what it already did (after going through the "while" part).

void print_winner(void)
{
    // TODO
    int counter = 1;
    do
    {
        counter = 0;
        for (int b = 0; b < candidate_count - 1; b++)
        {    
            if (candidates[b].votes > candidates[b + 1].votes)
            {
                swap_int(candidates[b].votes, candidates[b + 1].votes);
                swap_string(candidates[b].name, candidates[b + 1].name);
                counter++;
            }
        }
    }
    while (counter != 0);

...

void swap_int(int x, int y)
{
        int temporary = x;
        x = y;
        y = temporary;
}

void swap_string(string x, string y)
{
        string temporary = x;
        x = y;
        y = temporary;
}

At first, I thought maybe the names weren't following the votes, but using debug I figured out they are. It seems my program gets stuck in an infinite loop of trying to bubble sort because it gets stuck at square 1 each time

1 Answer 1

0

Review the Week 2 Short Variables and Scope. Strings and integers are passed by value, so in swap_int(candidates[b].votes, candidates[b + 1].votes);, you're passing whatever those numbers are, not candidates[b].votes. Because of that, you're not doing anything to the candidates array. If you want to have a separate function, you should pass b into it, and it can do the swapping to the candidates at b and b+1 directly to the candidates array.

More broadly, though, you don't need to sort. You're just trying to find the candidate(s) with the maximum number of votes, so you can go through the array of candidates and if the current candidate has more votes than the current max, set the current max to that candidate's number of votes. Then you can go through the candidates array once more, and print everyone who has the max number of votes. This is O(n), where the bubble sort you're working with is O(n^2).

1
  • wow that was a much easier way to do it
    – Matthew
    Jun 24, 2020 at 21:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .