Jonte
Jonte

Reputation: 21

Reverse Bubble Sort Algorithm in C using only while loop

I am trying to create a reverse bubble sort algorithm. It works but the first output is a big crazy number that i dont understand. The remaining outputs seem to be sorted in descending order. Where is my code wrong?

   #include <stdio.h>

  void ft_rev_int_tab(int *tab, int size)
  {
   int i;
   int j;
    int k;

     i = 0;
     while (i < size) 
   {
     j = 0;
     while (j < size -i) 
      {
         if (tab[j] < tab[j+1]) 
             {
                 k = tab[j]; 
                 tab[j] = tab[j+1]; 
                 tab[j + 1] = k; 
             }
     j++;
   }
 i++;
   }
   }


 int main(void) 
   {
 int tab[] = {9, 320, 0, 113, 15};
  int size = sizeof(tab) / sizeof(*tab);

   ft_rev_int_tab(tab, size);
   for (int i = 0; i < size; i++)
     {
    printf ("%d\n", tab[i]);
   } 
   }

Upvotes: 1

Views: 355

Answers (2)

Thọ Đỗ Xu&#226;n
Thọ Đỗ Xu&#226;n

Reputation: 150

void ft_rev_int_tab(int *tab, int size) {
    int i;
    int j;
    int k;

    i = 0;
    while (i < size) {
        j = 0;
        while (j < size - i - 1) {
            if (tab[j] < tab[j + 1]) {
                k = tab[j];
                tab[j] = tab[j + 1];
                tab[j + 1] = k;
            }
            j++;
        }
        i++;
    }
}

Your condition in the nested while loop should be (j < size - i - 1) because you only need to check the value from tab[0] to tab[i-1]. Your if and swap checks tab[j] and tab[j+1], so when i is equal to the size of the array, you will compare it with a value outside of the array. In your example is the tab[5]'s value.

Upvotes: 2

MikeCAT
MikeCAT

Reputation: 75062

i = 0; before while (i < size) is wrong. The condition j < size -i is equivalent to j < size when i is zero. In this case j will be at most size-1 and now tab[j+1] is out-of-range.

It should be changed to i = 1;.

Upvotes: 1

Related Questions