问题描述:

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!

网友答案:
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--)
相关阅读:
Top