Quick Bubble Sort Question
Nov 28, 2012 at 4:26am UTC
Hey guys, having a minor bubble sort situation when I'm trying to arrange in descending order. My ascending order function works flawlessly but my descending one seems to be storing one integer from a previous loop when I go to print them out. Am I overlooking something?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
void ascending()
{
// Bubble sort for putting the array into ascending order
for (a=1; a<size; a++)
for (b=size-1; b>=a; b--)
{
if (nums[b-1] > nums[b])
{
t = nums[b-1];
nums[b-1] = nums[b];
nums[b] = t;
}
}
cout << "\nThe array in ascending order is:\n" ;
for (t=0; t<size; t++) cout << nums[t] << ' ' ;
cout << '\n' ;
}
void descending()
{
// Bubble sort for putting the array into descending order
for (a=0; a<size-1; a++)
for (b=0; b<size; b++)
{
if (nums[b] < nums[b+1])
{
t = nums[b+1];
nums[b+1] = nums[b];
nums[b] = t;
}
}
cout << "\nThe array in descending order is:\n" ;
for (t=0; t<size; t++) cout << nums[t] << ' ' ;
cout << '\n' ;
}
Any suggestions would be great, and let me know if you'd like the entire code. Thanks
Nov 28, 2012 at 5:21am UTC
The only difference between an ascending and descending sort should be the comparison used to determine if two elements should be swapped.
Topic archived. No new replies allowed.