Home > Software design >  Why aren't my for loops working in this bubble sort function in C
Why aren't my for loops working in this bubble sort function in C

Time:01-04

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;
      }
    }
  }
  
}

CodePudding user response:

Your not working implementation misses the initialization of j. So it iterates the inner loop only in the first iteration of the outer loop.

void bubbleDesc (int n, int array[])
{
  
  int i = 0, j = 0, temp;
  
  for (i; i < n - 1; i  )
  {
    j = 0; // this init is needed
    for (j; j < n - 1; j  )
    {
      if (array[j] < array[j   1])
      {
        temp = array[j   1];
        array[j   1] = array[j];
        array[j] = temp;
      }
    }
  }
  
}

CodePudding user response:

try to initial i= and j= 0 in for loop

  • Related