carrayssortingwhile-loopbubble-sort

Sorting array only with while and if


I get a message when I try to run the program. Why?

Segmentation fault

my code:

#include <stdio.h>

void sort_array(int *arr, int s);

int main() {
    int arrx[] = { 6, 3, 6, 8, 4, 2, 5, 7 };

    sort_array(arrx, 8);
    for (int r = 0; r < 8; r++) {
        printf("index[%d] = %d\n", r, arrx[r]);
    }
    return(0);
}

sort_array(int *arr, int s) {
    int i, x, temp_x, temp;
    x = 0;
    i = s-1;
    while (x < s) {
        temp_x = x;
        while (i >= 0) {
            if (arr[x] > arr[i]) {
                temp = arr[x];
                arr[x] = arr[i];
                arr[i] = temp;
                x++;
            }
            i++;
        }
        x = temp_x + 1;
        i = x;
    }
}

I think that the problem is in the if statement. What do you think? Why does it happen? I think that I use in positive way with the pointer to the array.


Solution

  • This loop in your program

        while (i >= 0) {
            //...
            i++;
        }
    

    does not make sense because i is increased unconditionly.

    The program can look the following way

    #include <stdio.h>
    
    void bubble_sort( int a[], size_t n )
    {
        while ( !( n < 2 ) )
        {
            size_t i = 0, last = 1;
    
            while ( ++i < n )
            {
                if ( a[i] < a[i-1] )
                {
                    int tmp = a[i]; 
                    a[i] = a[i-1];
                    a[i-1] = tmp;
                    last = i;
                }
            }
    
            n = last;
        }
    }   
    
    int main( void ) 
    {
        int a[] = { 6, 3, 6, 8, 4, 2, 5, 7 };
        const size_t N = sizeof( a ) / sizeof( *a );
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
        printf( "\n" );
    
        bubble_sort( a, N );
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
        printf( "\n" );
    
        return 0;
    }
    

    The program output is

    6 3 6 8 4 2 5 7 
    2 3 4 5 6 6 7 8 
    

    If you want that the sorting function had only one while loop then you can implement it the following way

    void bubble_sort( int a[], size_t n )
    {
        size_t i = 0;
    
        while ( ++i < n )
        {
            if ( a[i] < a[i-1] )
            {
                int tmp = a[i]; 
                a[i] = a[i-1];
                a[i-1] = tmp;
                i = 0;
            }
        }
    }