【发布时间】:2017-07-03 10:04:30
【问题描述】:
您好,我编写了一个程序来使用冒泡排序对多维数组进行排序。我发现随着维度的增加对多维数组进行排序有点困难,所以我使用了一种技术:将多维数组复制到线性数组,然后对后者进行排序,然后将其复制回原始数组:
#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;
}
输出:
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,
- 代码工作正常,易于管理任何数组,无论维数如何。这是一个好方法还是有其他更好的选择?
【问题讨论】:
-
const int size = d1 * d2 * d3; -
@LWimsey:我编辑了代码。
int那里是必须的吗? -
是的,因为你不能声明一个没有类型的变量
-
您可以对数组进行就地排序,就像我的示例一样。数组将其数据存储在连续内存中,因此您只需要知道第一个元素的地址和最后一个元素的地址。一旦你有了这两个项目,那么任何传统的排序算法都可以工作,因为它只是一个线性序列。
-
@Lee_Wong Here is another example。我不想将这些示例作为答案发布,因为我不知道您是在寻找通用的多维数组排序,还是在寻找对多维数组进行排序的更简单的代码。
标签: c++ sorting multidimensional-array