C语言 C 编程。对二维数组中的行进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26681781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C programming. Sorting rows in a 2D array
提问by amstl14
I'm trying to sort the elements within the individual rows of a 2Darray. I understand how to sort the elements inside a 1Darray, but I am having serious trouble getting it to sort the 2D.
我正在尝试对2D数组的各个行中的元素进行排序。我了解如何对1D数组中的元素进行排序,但我很难让它对2D.
Code for the 1Darray:
1D数组代码:
for (i = 0; i < size; i++)
{
for (j = i +1; j < size; ++j)
{
if (array2[i] > array2[j])
{
swap = array2[i];
array2[i] = array2[j];
array2[j] = swap;
}
}
}
What I want to do:2DArray before sorting
我想做什么:2D排序前的数组
9 2 0 1 6 3
0 9 1 2 3 8
4 2 5 4 3 6
3 6 4 3 9 3
0 2 1 2 0 4
4 1 9 4 2 7
2Darray after sorting:
2D排序后的数组:
0 1 2 3 6 9
0 1 2 3 8 9
2 3 4 4 5 6
3 3 3 4 6 9
0 0 1 2 2 4
1 2 4 4 7 9
My code for the 2Dso far:
2D到目前为止我的代码:
size: the user defined dimensions (in the above case it is 6)
尺寸:用户定义的尺寸(在上述情况下为 6)
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
if(array[i][j] > array[i][j+1])
{
swap = array[i][j];
array[i][j] = array[i][j+1];
array[i][j+1] = swap;
}
}
}
Any help or advice would be much appreciated. Thank you all.
任何帮助或建议将不胜感激。谢谢你们。
回答by Amit Sharma
If you want to use your single array sorting algorithm (bubble sort)to sort the two dimensional array then you have to add the another forloop: An outer forloop which will take care of each row. Let's say mis number of row and nis number of column.
如果要使用单数组排序算法(bubble sort)对二维数组进行排序,则必须添加另一个for循环:一个for处理每一行的外循环。假设m是行n数和列数。
for(k=0; k< m; k++) {
for (i = 0; i < n; i++) {
for (j = i +1; j < n; ++j) {
if (array2[k][i] > array2[k][j]) {
int swap = array2[k][i];
array2[k][i] = array2[k][j];
array2[k][j] = swap;
}
}
}
}
But this is not an efficient approach to sort the array, it's time complexity will be O(mn^2)
但这不是对数组进行排序的有效方法,它的时间复杂度为 O(mn^2)
回答by Nikhil
copy all the elements of the 2d array into an 1d array then apply any sorting algorithm on 1d array & then copy back the sorted 1d array to the 2d array. please don't mind if you have a better solution then post it that will be helpfull for me.
将二维数组的所有元素复制到一维数组中,然后对一维数组应用任何排序算法,然后将排序后的一维数组复制回二维数组。如果您有更好的解决方案,请不要介意,然后发布它,这对我有帮助。
回答by Divyanshi
You can simply use STL to sort 2D array row-wise..
您可以简单地使用 STL 按行对二维数组进行排序。
for (i=0;i<n;i++){
for ( j=0;j<n;j++){
cin>>a[i][j];
}
sort(a[i],a[i]+n);
}
回答by Dilip Rathore
int tmp,l;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
tmp = a[i][j];
l = j + 1;
for (int k = i; k < 2; k++) {
while (l < 2) {
if (tmp < a[k][l]) {
tmp = a[k][l];
a[k][l] = a[i][j];
a[i][j] = tmp;
}
l++;
}
l = 0;
}
}
}

![C语言 警告:指针和整数之间的比较[默认启用]](/res/img/loading.gif)