二维数组的线性排序 [英] Linear Sort of a 2D Array

查看:81
本文介绍了二维数组的线性排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C编程的新手,正在尝试准备一些排序程序.我编写了线性/常规排序程序.

I am a newbie to C programming and was trying to prepare some sorting programs. I made the program of linear/ normal Sorting.

现在,我想制作一个程序来对2D数组进行排序. 即矩阵是否为

Now I want to make a program to sort 2D array. i.e. If the matrix is

4  6  1
3  2  9
5  7  8

那么结果应该是

1  2  3
4  5  6
7  8  9

推荐答案

由于您希望将2D数组按行进行排序,而这恰好是多维数组在C中的存储顺序,因此您可以假设它是一维数组并以这种方式对其进行排序.

Since you want your 2D array to be sorted row-wise, which happens to be the order in which multidimensional arrays are stored in C, you could pretend it is a 1D array and sort it that way.

假设您有一个函数void sort(int[], int size);,该函数需要一个指向1D数组的第一个元素及其大小的指针,您可以这样做

Assuming you have a function void sort(int[], int size); that takes a pointer to the first element of a 1D array and its size, you could do

int a[3][3] = {{4,6,1}, {3,2,9}, {5,7,8}};
sort(&a[0][0], 9);

自然,这仅适用于真正的2D数组,而不适用于指针数组,这就是动态分配的2D数组通常在C中实现的方式.

Naturally, this only works for true 2D arrays, not for arrays of pointers, which is how dynamically allocated 2D arrays are often implemented in C.

这篇关于二维数组的线性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆