[Solved] How to implement bubble sort in C. [closed]


Try this:

void bubble_sort(int m, int a[100000])
{
    int i, ok = 0, v, n = m;
    while ( !ok )
    {
        ok = 1;
        for ( i=0; i < m-1; ++i )
        {
            if ( *(a+i) > *(a+i+1) ) 
            { 
                v = *(a+i); 
                *(a+i) = *(a+i+1); 
                *(a+i+1) = v; 
                ok = 0;
            }
        }

        m--;
    }

    for ( i = 0; i < n; ++i )
        printf("%i ", a[i]);
}

Basically, initialize ok (local variables are initialized with garbage values). You also must set ok = 1 when entering the loop and ok = 0 if a swap took place. There’s no point in using a for loop, a while loop is more readable. m = m - 1 can be replaced with m--, it’s the same thing and you write less code.

8

solved How to implement bubble sort in C. [closed]