Write a program that uses Bubble Sort to sort integers in a 2 dimensional array in ascending order
如问题所示,我需要使用气泡排序对二维数组进行排序。这应该适用于任何n*m数组。
我知道,我们不应该不做任何尝试就提出问题。但是我的日程安排很紧,现在我正在学习C++。我找不到任何包含合适信息的链接来对此进行编码。
如果有人能帮我,那就太好了
可以将指向二维数组第一行的指针强制转换为指向int的指针,并将数组排序为一维数组。
给你
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | #include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> void bubble_sort( int *a, size_t n ) { for ( size_t last /* = n */; not ( n < 2 ); n = last ) { for ( size_t i = last = 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; } |
程序输出可能看起来像
1 2 3 4 5 6 7 | 7 3 8 7 6 8 5 0 10 9 9 3 0 3 3 5 6 7 7 8 8 9 9 10 |
另一种方法是将函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> template <typename T, size_t N, size_t M> void bubble_sort( T ( &a )[N][M] ) { for ( size_t n = N * M, last /* = n */; not ( n < 2 ); n = last ) { for ( size_t i = last = 1; i < n; i++ ) { if ( a[i / M][i % M] < a[( i - 1 ) / M][( i - 1 ) % M] ) { std::swap( a[i / M][i % M], a[( i - 1 ) / M][( i - 1 ) % M] ); 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( a ); 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; } |