Search code examples
csortingrecursionbubble-sort

Recursive Bubble Sort in C


I am unable to find the error in the silly recursive bubble-sort code below. Could somebody tell why it is not working correctly? Thanks in advance.

#include <stdio.h>

int b[8] = { -9, 9, 89, 78, 56, 45, 34, 89 };

void print(int n)
{
    int i; 

    for (i = 0; i < n; i++)
        printf("%d\t", b[i]);

    printf("\n");
}

void rb(int n)
{
    if(n == 0) 
        return;

    int i, j;
    for (i = 0; i < n - 1; i++) {
        if (b[i + 1] > b[i])
            j = b[i + 1];

        b[i + 1] = b[i];
        b[i] = j;
    }

    rb(n - 1);
}

int main()
{
    print(8); 
    rb(8); 
    print(8); 

    return 0;
}

Solution

  • your if statement in the for loop really looks like this below, need to add "{" and "}" around the three lines of code that does the swapping. Also since j is only used in the swap part of the code. if you had scoped 'j' inside of the 'if' block. the compiler would have found this issue.

    void rb(int n)
    {
        if(n==0)
            return;
        int i;
        for(i=0;i<n-1;i++)
        {
            if(b[i+1]>b[i]) {
                /* swap the two values and scope j as tightly as possible */
                int j=b[i+1]; 
                b[i+1]=b[i];
                b[i]=j;
            }
        }
        rb(n-1);
    }