I need assistance in writing the code for bubble sort the array

Sir, do I have passed the exam?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void bubble_sort( int a[], size_t n )
{
    int sorted = 1;

    for ( size_t i = 0; sorted && ++i < n;  )
    {
        sorted = !( a[i] < a[i-1] );
    }

    if ( sorted )
    {
        puts( "The array is already sorted" );
        return;
    }

    while ( !sorted && 1 < n-- )
    {
        int *prev = a, *next = a;

        sorted = 1;

        for ( size_t i = 0; i < n; ++i )
        {
            ++next;
            if ( *next < *prev ) 
            {
                int tmp = *prev;
                *prev = *next;
                *next = tmp;

                sorted = 0;
            }
            ++prev;
        }
    }
}

#define N   10

int main( void )
{
    int a[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;

    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\n" );

    srand( ( unsigned int )time( NULL ) );

    for ( size_t i = 0; i < N; i++ ) a[i] = rand() % N;

    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" );
}

The program output might look like

0 1 2 3 4 5 6 7 8 9 
The array is already sorted
0 1 2 3 4 5 6 7 8 9 

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

Browse More Popular Posts

Leave a Comment