c#二维数组排序
时间: 2025-03-22 15:03:59 浏览: 39
### C# 中二维数组的排序方法
在 C# 中,二维数组本质上是一个多维数据结构,无法像一维数组那样直接通过内置函数 `Array.Sort` 进行排序。然而,可以通过自定义逻辑实现对二维数组的排序操作。
#### 自定义排序方式
可以将二维数组视为多个一维数组集合,并针对每一行或某一特定条件进行排序。以下是一些常见的方式:
1. **按某一行或某一列排序**
如果希望按照某个固定行或者列来决定整个二维数组的顺序,则需要提取该行/列作为比较依据。
2. **逐行列内部排序**
对于每行单独执行排序算法(如选择排序、冒泡排序等),从而使得各子数组有序排列。
下面是具体代码示例展示如何基于不同需求完成上述两种类型的排序:
```csharp
using System;
class Program {
static void Main() {
// 定义一个简单的3x4矩阵
int[,] matrix = new int[3, 4]{
{9,8,7,6},
{5,4,3,2},
{1,0,-1,-2}
};
Console.WriteLine("原始矩阵:");
PrintMatrix(matrix);
// 方式一: 整体转换成List<Tuple<int,int>>形式再排序(假设以第零列为关键字)
SortByColumn(ref matrix, 0);
Console.WriteLine("\n按第一列升序后的矩阵:");
PrintMatrix(matrix);
// 方式二: 各自行独立排序
RowWiseSort(ref matrix);
Console.WriteLine("\n各行分别从小到大排序后的矩阵:");
PrintMatrix(matrix);
}
private static void PrintMatrix(int[,] mat){
for (int r=0;r<mat.GetLength(0);r++){
for (int c=0;c<mat.GetLength(1);c++)
Console.Write(mat[r,c]+" ");
Console.WriteLine();
}
}
/// <summary>
/// 将二维数组按指定列排序.
/// </summary>
public static void SortByColumn(ref int[,] array, int columnIndex) {
var rowsCount = array.GetLength(0);
var columnsCount = array.GetLength(1);
if(columnIndex >=columnsCount ||columnIndex <0 ) throw new ArgumentException();
Tuple<int[], int>[] tuples=new Tuple<int[], int>[rowsCount];
for (var rowIdx = 0;rowIdx<tuples.Length ;++rowIdx ){
var currentRow=new int[columnsCount ];
Array.Copy(array,currentRow,rowIdx*columnsCount ,currentRow.Length );
tuples[rowIdx]=Tuple.Create(currentRow,columnIndex);
}
Array.Sort(tuples,(a,b)=> a.Item1[a.Item2].CompareTo(b.Item1[b.Item2]));
for(var idx=0;idx<array.GetLength(0)*array.GetLength(1)/array.GetLength(1);++idx )
Array.Copy(tuples[idx].Item1,array,idx*tuples[idx].Item1.Length,tuples[idx].Item1.Length );
}
/// <summary>
/// 实现行内元素排序功能.
/// </summary>
public static void RowWiseSort(ref int[,] array){
var rowCount=array.GetLength(0);
var colCount=array.GetLength(1);
for(int rowIndex=0;rowIndex<rowCount;++rowIndex){
int[] temp=new int[colCount];
Buffer.BlockCopy(array,temp,rowIndex*colCount,colCount*sizeof(int));
Array.Sort(temp);
Buffer.BlockCopy(temp,array,rowIndex*colCount,colCount*sizeof(int));
}
}
}
```
此程序展示了两种不同的排序策略:一种是对整个二维数组根据选定的一列重新安排;另一种则是让每个单行都成为已排序状态。这两种技术都可以灵活应用于实际场景之中[^1][^2].
### 注意事项
当处理更复杂的排序标准时,可能还需要考虑稳定性以及其他性能因素。此外,在某些情况下,如果频繁访问和修改大型稀疏矩阵的数据项,那么采用其他更适合此类用途的数据结构可能会更加高效。
阅读全文
相关推荐
















