views:

448

answers:

2

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!

+3  A: 

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.

Moron
I hope this is for a homework assignment.
Jeremy Petzold
Yea, so I just slammed my head on my desk. Indeed I did mean j and not i, figured it would be something stupidly simple like that. Thanks for the fresh set of eyes!
Jeff
@Jeff: Yeah, your pointer usage seems fine. Only your typing skills need improvement :)
Moron
+1  A: 

Bubble sort works the same no matter if you are talking an array or a linked list (pointers).

The only catch is that rather than swapping the location of two adjacent items in an array, you are swapping pointer values between two adjacent list elements.

The algorithm is the same.

Jeremy Petzold
Nothing in the OP's question or code suggests that he's dealing with linked lists.
sepp2k
Your response assumes I paid attention enough to look at his code. Bad /. habits.
Jeremy Petzold