Array sorting in C -- Error in float version

Asked

Viewed 20 times

0

For some reason I don’t know, when I change the type of my int function to float it just doesn’t work properly:

void organizeArray(float array[], int size){
  int aux;
  for (int i = 1; i < size; i++)
  {
    for (int j = 0; j < size; j++)
    {
      if (array[j] >= array[j + 1])
      {
        aux = array[j];
        array[j] = array[j+1];
        array[j+1] = aux;
      }
    }
  }
}

When I change the function parameter to int and enter an int array it works correctly, but when I use float it doubles the 0 at the beginning of the ordered version.

Input: float array[10] = {5, 8, 4, 7, 9, 6, 3, 0, 2, 1};
Output: 0 0 1 2 3 4 5 6 7 8 /Why are two zeros coming out? Any idea how to fix?

  • Assuming size be the size of your array note that inside the loop for (int j = 0; j < size; j++) you reference the position j+1, that is, at the end of the loop it is comparing to a memory position outside the area of its array. Another thing that doesn’t make sense: this more external loop, with the variable i, Shouldn’t you repeat only if there’s a trade? Suppose your array is already sorted then there is no need to keep repeating the check.

  • I think I have to study more about vector ordering so I don’t think I understand the code yet or why my problem, thank you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.