【发布时间】:2015-09-17 15:03:40
【问题描述】:
在二维数组排序中,正如我所见,他们只是将其复制到一维数组并对其进行排序。但是有没有其他方法可以在不使用一维数组的情况下对二维数组进行排序。
// 代码
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int rows, columns;
int k = 0, temp;
int rowColumn;
//getting rows and columns number
cout<<"Enter number of rows";
cin>>rows;
cout<<"Enter number of columns";
cin>>columns;
//declaring and intitalizing oneD and twoD array
rowColumn = rows * columns;
int arr[rows][columns];
int oneDArr[rowColumn];
//Fill 2D array by user
cout<<"Fill 2D array row wise"<<endl;
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
cin>>arr[i][j];
}
}
//Taking 2d array in 1d array
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
oneDArr[k] = arr[i][j];
k++;
}
}
//Bubble sort perform on 1d array
for(int j=1;j<rowColumn;j++)
{
for(int i=0; i<rowColumn; i++)
{
if(oneDArr[i]>oneDArr[i+1])
{
temp=oneDArr[i];
oneDArr[i] = oneDArr[i+1];
oneDArr[i+1]=temp;
}
}
}
//rearranging the oneD array to twoD array
k = 0;
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
arr[i][j] = oneDArr[k];
k++;
}
}
//Displaying sorted 2d Array
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
cout<<arr[i][j]<<"\t";
}
cout<<"\n";
}
}
有没有其他方法可以有效地对二维数组进行排序。
【问题讨论】:
-
您可以设置访问二维数组的方法,以便一维算法可以无缝地对其进行处理。大多数情况下,您可以使用改进冒泡排序的众多排序算法中的任何一种。
-
C Array sorting tips 的可能重复项
-
@Politank-Z - 如果你保证阵列的存储是连续的,那将是相对微不足道的。
-
首先,您必须解释“二维数组的排序”是什么意思。对于这样的排序,有很多完全不同的理解。当你不清楚什么你想做什么时,讨论如何做某事是没有意义的。
-
@Mr.Llama 即使你不能保证,而且你知道数组的宽度,你仍然在微不足道的距离。
标签: c++