I was having this problem to which I have come to the solution through the trial and error process but I have no idea why my bubble sort function wasn't working in the first place.
The problem had to do with the for-loops inside my function. Specifically when declaring and defining my i and j variables.
In my version of C I can define variables inside my for-loop parameter, but I can't declare them, so I do both the declaration and definition outside.
Doing so though made my function not work as intended as it didn't sort my array at all.
Though after declaring the variables outside but defining them inside the for-loop parameter to my surprise the function worked properly. My problem is I have no idea why.
Here I am providing both the working version and the non-working version:
Non-Working Version:
void bubbleDesc (int n, int array[])
{
int i = 0, j = 0, temp;
for (i; i < n - 1; i++)
{
for (j; j < n - 1; j++)
{
if (array[j] < array[j + 1])
{
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
Working Version:
void bubbleDesc (int n, int array[])
{
int i, j, temp;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - 1; j++)
{
if (array[j] < array[j + 1])
{
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
Your not working implementation misses the initialization of j. So it iterates the inner loop only in the first iteration of the outer loop.
Thought, better would be to limit the scope of
jand declare it only in the block where it is used, i.e.,for (int j=0;...){...}