Search code examples
cbubble-sort

How to keep while loop in bubble sort function in C


I'm trying to make my own bubble-sort function in C.

As you can see in the code below this, I'm trying to only using while / if loop to create this function. I put 5 numbers (1,3,2,5,4) so that size of array of this would be 5, and I got 5 (I checked it with Python(C)tutor. However, It works well until tab[j] gets 3. I'm trying to figure it out, but couldn't figure it out why it keeps going out when tab[j] gets 3.

Could you anybody explain what's wrong to me? I would appreciate it.

Here is my code below:

#include <stdio.h>

void ft_sort_integer_table(int *tab, int size)
{
    int i;
    int j;
    int tem;

    i = 0;
    j = 0;
    while(tab[i] < size)
    {
        if(tab[j] > tab[j+1])
        {
            tem = tab[j];
            tab[j] = tab[j+1];
            tab[j+1] = tem;
            printf("%d ", tab[j]);
            j++;
        }
        else if(tab[j] < tab[j+1])
        {
          printf("%d ",tab[j]);
          j++;
        }
        i++;
    }
}

int main(void)
{
    int tab[] = {1,3,2,5,4};
    int size = sizeof(tab)/sizeof(*tab);
    ft_sort_integer_table(tab, size);
    return(0);
}

Solution

  • I'm trying to figure it out, but couldn't figure it out why it keeps going out when tab[j] get 3.

    From your code above, j increment in the same fashion as i. That means both variables will have the same value since j will be incremented by one after the if-then-else statement, and i will also be incremented by one at the end of each loop. Therefore, tab[j] is referencing the same value as tab[i]

    With that being said, the boolean condition in the while loop checks whether the value in the tab[i] is less than the value of size.

    When i == 3, tab[i] == 5 since in the loop, only the values in the array of index less then i are swapped/changed. Since the size variable holds that value of 5, tab[i] < size will result in a false value and exit the loop.

    More information on bubble sort can be found here, https://www.geeksforgeeks.org/bubble-sort/