c#sort升序还是降序_C#按升序和降序排序数组

它应该是这样的:

public static bool IsArraySorted(int[] numbers)

{

bool? ascending = null;

for (int i = 1; i < numbers.Length; i++)

{

if (numbers[i - 1] != numbers[i])

{

bool ascending2 = numbers[i - 1] < numbers[i];

if (ascending == null)

{

ascending = ascending2;

}

else if (ascending.Value != ascending2)

{

return false;

}

}

}

return true;

}

注意使用升序变量来保存数组的“方向”.它是在第一次找到两个不同的元素时初始化的.

请注意,如果需要,您甚至可以返回数组的“方向”:

public static bool IsArraySorted(int[] numbers, out bool isAscending)

{

isAscending = true;

bool? ascending = null;

在if内(升序== null)

if (ascending == null)

{

ascending = ascending2;

isAscending = ascending2;

}

这是基于IEnumerable< TSource>的通用版本:

public static bool IsSorted(IEnumerable source, out bool isAscending, Comparer comparer = null)

{

isAscending = true;

if (comparer == null)

{

comparer = Comparer.Default;

}

bool first = true;

TSource previous = default(TSource);

bool? ascending = null;

foreach (TSource current in source)

{

if (!first)

{

int cmp = comparer.Compare(previous, current);

if (cmp != 0)

{

bool ascending2 = cmp < 0;

if (ascending == null)

{

ascending = ascending2;

isAscending = ascending2;

}

else if (ascending.Value != ascending2)

{

return false;

}

}

}

first = false;

previous = current;

}

return true;

}

注意使用bool first / TSource之前处理i – 1(以及for循环能够“跳过”第一个元素的事实)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值