Too many passes in bubble sort?

Back to General discussions forum

Vajorski     2017-08-06 23:05:49

My bubble sorter does one too many passes according to the problem answers, but does the correct number of swaps. I can't seem to figure out why, and I'm pretty much banging my head against a brick wall at this point. Any help?

/* Bubble sort algorithm. */

#include <iostream>
using namespace std;

int main(int argc, char** argv) 
{
    cout << "Enter data: ";
    int length;
    cin >> length;
    int holder[length];
    for (int i = 0; i < length; i++)
    {
        cin >> holder[i];
    }

    int passes = 0;
    int swaps = 0;

    for (int j = 0; j < length - 1; j++)
    {
        bool swapped = false;

        for (int k = 1 + j; k < length; k++)
        {
            if (holder[j] > holder[k])
            {
                int temp = holder[j];
                holder[j] = holder[k];
                holder[k] = temp;
                swaps++;
                swapped = true;
            }

        }
        if (!swapped)
        {
            break;
        }
        else if (j != length - 2)
        {
            passes++;
        }
    }

    cout << endl;

    for (int ii = 0; ii < length; ii++)
    {
        cout << " " << holder[ii];
    }


    cout << endl << " " << passes << " " << swaps;
    return 0;
}
Quandray     2017-08-07 06:53:59
User avatar

Hi,

It says "Take a pass through array, examining all pairs of adjacent elements". I don't think your code is doing that.

Vajorski     2017-08-07 15:27:34

I don't think it does either now that you mention it. I'm gonna go back and rewrite it, and see if I can come up with the correct solution. Thanks for the input!

Please login and solve 5 problems to be able to post at forum