User2529 User2529 - 3 months ago 7
C++ Question

Write a program that uses Bubble Sort to sort integers in a 2 dimensional array in ascending order

as the question shows, I need to use bubble sort to sort a 2 dimensional array. This should work for any N*M array.

I know we are not supposed to ask questions without attempting anything first. But I am on a very tight schedule and I'm learning c++ now. I couldn't find any links with suitable information to code this.

If someone could help me with this, it'd be great

Answer

You can cast pointer to the first row of a two-dimensional array to pointer to int and sort the array as a one-dimensional array.

Here you are

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>

void bubble_sort( int *a, size_t n )
{
    for ( size_t last = n; !( n < 2 ); n = last )
    {
        last = 1;

        for ( size_t i = 1; i < n; i++ )
        {
            if ( a[i] < a[i-1] )
            {
                std::swap( a[i], a[i-1] );
                last = i;
            }
        }
    }
}

int main()
{
    const size_t N = 3;
    const size_t M = 4;

    int a[N][M];

    std::srand( ( unsigned int )std::time( nullptr ) );

    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < M; j++ ) a[i][j] = std::rand() % ( M * N );
    }

    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < M; j++ ) 
        {
            std::cout << std::setw( 2 ) << a[i][j] << ' ';
        }
        std::cout << std::endl;
    }

    std::cout << std::endl;

    bubble_sort( reinterpret_cast<int *>( a ), N * M );

    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < M; j++ ) 
        {
            std::cout << std::setw( 2 ) << a[i][j] << ' ';
        }
        std::cout << std::endl;
    }

    return 0;
}

The program output might look like

 7  3  8  7 
 6  8  5  0 
10  9  9  3 

 0  3  3  5 
 6  7  7  8 
 8  9  9 10