Reputation: 107
So I want to write a bubble sort code that sorts random numbers in descending order. This is the code I wrote:
void BubbleSort(int data[], int size)
{
for (int i = size - 1; i >= 0; i--)
{
for (int j = 0; j <=size-1; j++)
{
if (data[j] <data[j + 1])
{
swap(data[j], data[j+1]);
}
}
}
}
Where swap is this:
void Swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
When I run the code it won't sort anything, it just keeps the random numbers in the same order as when they were generated. I am not sure what's wrong with my code, I tried to trace it on paper and it worked well; could it be something with the sort function?
Edit: I just fixed the outer and inner loop, yet it's still not sorting.
Thanks!
Upvotes: 1
Views: 3029
Reputation: 1262
for (int i = size - 1; i < 0; i--)
i < 0 is never true because you start with i > 0
change it to:
for (int i = size - 1; i >= 0; i--)
Upvotes: 2