首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#排序数组的升序和降序

C#排序数组的升序和降序
EN

Stack Overflow用户
提问于 2015-06-15 11:39:04
回答 8查看 12.3K关注 0票数 8

如果数组(数字)的元素按排序顺序(升序或降序),如果元素没有按任何排序顺序排列,则编写一个返回true的方法有困难。如果数组正在上升,我可以返回一个正确的布尔值,但我不知道如何在同一方法中检查降序。我目前有:

代码语言:javascript
运行
复制
public static bool IsArraySorted(int[] numbers)
{
    for (int i = 1; i < numbers.Length; i++)
    {
        if (numbers[i - 1] > numbers[i])
            return false;
    }

    return true;
}

谁能在如何检查排序降序数组方面提供帮助呢?干杯!

EN

Stack Overflow用户

发布于 2015-06-15 13:23:17

我的答案在哪里?我一小时前写的:

代码语言:javascript
运行
复制
public enum SortType
{
     unsorted   = 0,
     ascending  = 1,
     descending = 2
}

public static SortType IsArraySorted(int[] numbers)
{
    bool ascSorted = true;
    bool descSorted = true;

    List<int> asc = new List<int>(numbers);            

    asc.Sort();

    for (int i = 0; i < asc.Count; i++)
    {
        if (numbers[i] != asc[i]) ascSorted = false;
        if (numbers[asc.Count - 1 - i] != asc[i]) descSorted = false;
    }

    return ascSorted ? SortType.ascending : (descSorted? SortType.descending : SortType.unsorted);
}

示例:

票数 1
EN
查看全部 8 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30844241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档