T. Schoonbeek T. Schoonbeek - 2 months ago 6
C Question

Sorting values in an array in C

I am very new to programming. For an assignment I have to make a function that can sort the array in ascending order. I have written a function, however it does not work entirely. I have read a lot of questions about cases like this on this forum already (searched for bubble sort for example), however I still can't work out my problem.

my code:

void sortOnValue(float *values, int size)
{
int i, d;
float swap;

for (i = 0; i < (size - 1); i++)
{
for (d = 0; d < (size - 1 - i); d++);
{
if (values[d] > values[d+1])
{
swap = values[d];
values[d] = values[d+1];
values[d+1] = swap;
}
}
}
}

void main()
{
int i;
float x, y;
float val[10]; //1.5, 2.2, 7.3, 9.2, 7.4, 7.5, -8.0, 1.5, 12
val[0] = 1.5;
val[1] = 2.2;
val[2] = 7.3;
val[3] = 9.2;
val[4] = 7.4;
val[5] = 7.5;
val[6] = -8.0;
val[7] = 1.5;
val[8] = 12;

printValues(val, 10);
sortOnValue(val, 10);
printValues(val, 10);
}


my output:

Values: 1.500 -8.000 2.200 7.300 9.200 7.400 7.500 0.000 1.500 12.000


Any idea why it is not working? I think it might be because the loop ends before it should, however I am not sure.
Also, is there a more efficient way of assigning values to an array than what I did?

Thanks in advance for any help!

Answer

Look closely at this line:

   //              what's this? -------v
   for (d = 0; d < (size - 1 - i); d++);
   {

You have a stray semicolon at the end of this for. As a result, what you have here is an empty loop. Then the block below it runs every time.

Get rid of it and the program runs as expected.

As a matter of style, it's good practice to have the opening brace of a block on the same line as the statement that starts it as follows:

   for (d = 0; d < (size - 1 - i); d++) {

That helps to reduce the chances of something like this happening.

Also, if you want to initialize an array, you can do it like this:

float val[10] = { 1.5, 2.2, 7.3, 9.2, 7.4, 7.5, -8.0, 1.5, 12, 9.9 };

Note that previously you weren't initializing all 10 elements in the array. I added one more element here to fill in the whole thing.