How do you use a bubble sort with pointers in c++?

Soully picture Soully · Feb 6, 2010 · Viewed 12k times · Source

So here's what I have so far:

void sortArray(int amountOfScores, int* testScores)
{
    for(int i = 0; i < amountOfScores; i++)
    {
        for(int j = 0; j < amountOfScores-1; j++)
        {
            if(*(testScores+i) > *(testScores+j+1))
            {
                int temp = *(testScores+j);
                *(testScores+j) = *(testScores+j+1);
                *(testScores+j+1) = temp;
            }
        }
    }       
    for(int i = 0; i < amountOfScores; i++)
    {
        cout << *(testScores+i) << endl;
    }
}

Basically I'm trying to read in however many numbers the user wants to input, then sort them in ascending order. Catch is I have to use pointers and I've never really understood them. This code above works for 3 numbers, however, adding any more causes it to not sort them...I've tried trouble shooting as best I could but without any knowledge in pointers I don't know what I'm looking for.

Thanks for the help!

Answer

Aryabhatta picture Aryabhatta · Feb 6, 2010

You problem might be here:

    if(*(testScores+i) > *(testScores+j+1)) 

Did you mean:

        if(*(testScores+j) > *(testScores+j+1)) 

(Note i replaced by j).

btw, in Bubble sort, if there are no swaps, you should break. This will cause a speed up in some cases.