Reputation: 849
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!
Upvotes: 3
Views: 12604
Reputation: 1107
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.
Upvotes: 1
Reputation:
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.
Upvotes: 3