Hello I have written a program to sort a multi-dimension array using bubble sort. I found it a bit difficult to sort a multi-dimension array as much as dimensions increase so I used a technique: copying a multi-dim array to a linear one then sort the latter then copy back it to the original:
#include <iostream>
int main(){
const int d1 = 2, d2 = 3, d3 = 2;
int array[d1][d2][d3] = {
{ {5 , 7}, {2, 55}, {17, 23} },
{ {57, 77}, {1, 0} , {21, 16} }
};
std::cout << "Before sorting: " << std::endl << std::endl;
for(int i(0); i < 2; i++){
for(int j(0); j < 3; j++){
for(int k(0); k < 2; k++)
std::cout << array[i][j][k] << ", ";
std::cout << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
const int size = d1 * d2 * d3;
int array2[size] = {0};
memcpy(array2, array, sizeof(int) * size);
for(int i(0); i < size; i++)
std::cout << array2[i] << ", ";
std::cout << std::endl << std::endl;
for(int i(0); i < size; i++)
for(int j(i + 1); j < size; j++)
if(array2[i] > array2[j]){
array2[i] ^= array2[j];
array2[j] ^= array2[i];
array2[i] ^= array2[j];
}
for(int i(0); i < size; i++)
std::cout << array2[i] << ", ";
std::cout << std::endl << std::endl;
memcpy(array, array2, sizeof(int) * size);
std::cout << "After sorting:" << std::endl << std::endl;
for(int i(0); i < 2; i++){
for(int j(0); j < 3; j++){
for(int k(0); k < 2; k++)
std::cout << array[i][j][k] << ", ";
std::cout << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
return 0;
}
The output:
Before sorting:
5, 7, 2, 55, 17, 23,
57, 77, 1, 0, 21, 16,
5, 7, 2, 55, 17, 23, 57, 77, 1, 0, 21, 16,
0, 1, 2, 5, 7, 16, 17, 21, 23, 55, 57, 77,
After sorting:
0, 1, 2, 5, 7, 16,
17, 21, 23, 55, 57, 77,
- The code works fine and easy to manage any array however the number of dimensions. Is this a good way or there's another better alternative?
const int size = d1 * d2 * d3;intthere?