C# sorting arrays in ascending and descending order

It should be something like:

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;
}

Note the use of the ascending variable to save the "direction" of the array. It is initialized the first time two elements that are different are found.

Note that if you want, you can even return the "direction" of the array:

public static bool IsArraySorted(int[] numbers, out bool isAscending)
{
    isAscending = true;
    bool? ascending = null;

and inside the if (ascending == null)

if (ascending == null)
{
    ascending = ascending2;
    isAscending = ascending2;
}

This is a generic version based on IEnumerable<TSource>:

public static bool IsSorted<TSource>(IEnumerable<TSource> source, out bool isAscending, Comparer<TSource> comparer = null)
{
    isAscending = true;

    if (comparer == null)
    {
        comparer = Comparer<TSource>.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;
}

Note the use of bool first/TSource previous to handle the i - 1 (and the fact that the for cycle was able to "skip" the first element)


Using Linq -

public static bool IsArraySorted(int[] numbers)
{
    var orderedAsc = numbers.OrderBy(a => a);
    var orderedDes = numbers.OrderByDescending(a => a);

    bool isSorted = numbers.SequenceEqual(orderedAsc) ||
                    numbers.SequenceEqual(orderedDes);
    return isSorted;
}

This uses one loop to test both cases:

public static bool IsSorted<T>(IEnumerable<T> items, Comparer<T> comparer = null)
{
    if (items == null) throw new ArgumentNullException("items");
    if (!items.Skip(1).Any()) return true;  // only one item

    if (comparer == null) comparer = Comparer<T>.Default;
    bool ascendingOrder = true; bool descendingOrder = true;

    T last = items.First();
    foreach (T current in items.Skip(1))
    {
        int diff = comparer.Compare(last, current);
        if (diff > 0)
        {
            ascendingOrder = false;
        }
        if (diff < 0)
        {
            descendingOrder = false;
        }
        last = current;
        if(!ascendingOrder && !descendingOrder) return false;
    }
    return (ascendingOrder || descendingOrder);
}

usage:

int[] ints = { 1, 2, 3, 4, 5, 6 };
bool isOrderedAsc = IsSorted(ints); // true
bool isOrderedDesc = IsSorted(ints.Reverse()); //true

If you make it an extension method you can use it with any type:

bool ordered = new[]{"A", "B", "C"}.IsSorted();

public static boolean checkSortedness(final int[] data) 
{
    for (int i = 1; i < data.length; i++) 
    {
        if (data[i-1] > data[i]) {
            return false;
        }
    }
    return true;
}

Where is my answer? I wrote it about an hour ago:

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);
}

Example:


Comments

  1. Paul

    • 2019/3/14

    C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone 

  2. Robinson

    • 2019/4/17

    News Citigroup Inc.C. Consumer-Service Stocks Have Underperformed. Why It's Their Time to Shine. The Price to Earnings (P/E) ratio, a key valuation measure, is calculated by dividing the stock's

  3. Jermaine

    • 2017/2/25

    C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on.

  4. Bruce

    • 2016/10/13

    Citigroup, Inc. Common Stock (C) Stock Quotes - Nasdaq offers stock quotes & market activity data for US and global markets.

  5. Adan

    • 2015/8/13

    learn-c.org is a free interactive C tutorial for people who want to learn C, fast.

  6. Daniel

    • 2020/6/18

    Discover historical prices for C stock on Yahoo Finance. View daily, weekly or monthly format back to when Citigroup, Inc. stock was issued.

  7. Carl

    • 2021/1/21

    Amazon.com: C Programming Language, 2nd Edition: 8601410794231: Brian W. Kernighan, Dennis M. Ritchie: Books.

  8. Graham

    • 2021/7/24

    The Centers for Disease Control and Prevention (CDC) cannot attest to the accuracy of a non-federal website. Linking to a non-federal website does not constitute an endorsement by CDC or any of its employees of the sponsors or the information and products presented on the website. You will be

  9. Shepherd

    • 2016/1/30

    C is considered as a middle-level language because it supports the feature of both low-level and high-level languages. C language program is converted into 

  10. Jaxton

    • 2015/3/19

    c = a + b; Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’. C/C++ has many built-in operator types and they are classified as follows:

  11. Dibra

    • 2018/8/1

    The best site for C and C++ programming. Popular, beginner-friendly C and C++ tutorials to help you become an expert!

  12. Jones

    • 2015/11/2

    C. diff (also known as Clostridioides difficile or C. difficile) is a germ (bacterium) that causes severe diarrhea and colitis (an inflammation of the colon). It’s estimated to cause almost half a million infections in the United States each year. About 1 in 6 patients who get C. diff will get it again in the subsequent 2-8 weeks.

Comments are closed.

Recent Posts