第一次写文章,诚惶诚恐,希望自己能够开个好头,以后写出好文章。
我们知道数组排序是一个经典的话题了,每本数据结构书里面都有关于排序的章节。我们也可以使用各种语言实现这些排序算法,个人感觉在C#下,书写排序算法要简单的多,下面我以代码演示:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
1
public class OrderUtil
2![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
3![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
4
/// 默认升序排序
5
/// </summary>
6
/// <param name="train">待排序的数组</param>
7
/// <param name="index">排序的列</param>
8
/// <returns></returns>
9
public string[,] OrderbyCol(string[,] train, int index)
10![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
11
int col = train.GetLength(1);
12
int row = train.GetLength(0);
13
string[,] temp = new string[row,col];
14
int j;
15
int i;
16
int compareResult;
17
for (i = 0; i < train.GetLength(0); i++)
18![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
19
for (j = i+1; j < train.GetLength(0); j++)
20![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
21
compareResult = Comparer.Default.Compare(Convert.ToInt32(train[i, index]), Convert.ToInt32(train[j, index]));
22
if (compareResult.Equals(-1))
23![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
24
Array.Copy(train, j * train.GetLength(1), temp, 0 * train.GetLength(1), train.GetLength(1));
25
Array.Copy(train, i * train.GetLength(1), train, j * train.GetLength(1), train.GetLength(1));
26
Array.Copy(temp, 0 * train.GetLength(1), train, i * train.GetLength(1), train.GetLength(1));
27
}
28
}
29
}
30
return train;
31
}
32
}
使用Array类的copy方法完成复制,使用Comparer类的Compare方法完成排序,大家觉得这么写代码是不是简单了许多呢?