标签:C# GetLength object lists int 二维 new 排序 row
@[TOC](C# 实现二维数组的排序算法(代码))
//二维数组排序类
class toDimSort
{
//返回第row行的所有元素,是一个一维数组
public object[] GetRowByID(object[,] lists, int row)
{
if (row > (lists.GetLength(0) - 1))
throw new Exception("row超出最大的行索引号");
object[] tmp = new object[lists.GetLength(1)]
;
for (int i = 0; i < lists.GetLength(1); i++)
tmp[i] = lists[row, i];
return tmp;
}
//复制一行数据到指定的行上
public void CopyToRow(object[,] lists, int row, object[] tmp)
{
if (row > lists.GetLength(0) - 1)
throw new Exception("row超出最大的行索引号");
if (tmp.Length > lists.GetLength(1))
throw new Exception("row行数据超过二维数组的列数");
for (int i = 0; i < lists.GetLength(1); i++)
lists[row, i] = tmp[i];
}
//参数说明:lists-二维数组,orderCols-排序列索引号,type-0升序|1降序
public object[,] orderBy(object[,] lists, int[] orderCols, int type)
{
//这是一个二维数组,所以lists.GetLength(1)有几列,GetLength(0)有几行
//存放数据大的行和数据小的行,是否需要交换
object[] small = new object[lists.GetLength(1)];
object[] big = new object[lists.GetLength(1)];
int cmpResult;
for(int i = 0; i < lists.GetLength(0); i++)
{
for(int k = i+1; k < lists.GetLength(0); k++)
{
if(type.Equals(1)) //降序
{
for(int h = 0; h < orderCols.Length; h++)
{
int col = orderCols[h];
//比较第k行和第i行
object kh = lists[k, col];
object ih = lists[i, col];
cmpResult = Comparer.Default.Compare(kh, ih);
if (cmpResult.Equals(1)) //大数在k行,小数在i行,要换
{
small = GetRowByID(lists, i);
big = GetRowByID(lists, k);
CopyToRow(lists, i, big);
CopyToRow(lists, k, small);
}
if(cmpResult != 0)
break;
}
}
else //升序
{
for(int h =0; h <orderCols.Length; h++)
{
int col = orderCols[h];
//比较第k行和第i行
object kh = lists[k, col];
object ih = lists[i, col];
cmpResult = Comparer.Default.Compare(kh, ih);
if (cmpResult.Equals(-1)) //大数在i行,小数在k行,要换
{
small = GetRowByID(lists, k);
big = GetRowByID(lists, i);
CopyToRow(lists, i, small);
CopyToRow(lists, k, big);
}
if(cmpResult != 0)
break;
}
}
}
}
return lists;
}
}
标签:C#,GetLength,object,lists,int,二维,new,排序,row 来源: https://blog.csdn.net/wens17/article/details/100807186
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。