簡體   English   中英

試圖找出數組是否已排序

[英]Trying to figure out if an array is sorted

我試圖找出用戶輸入的數組是否已排序(不過不嘗試對其進行排序)。 如果用戶的輸入是從最小到最大的升序,那么我想寫一條消息,說“輸入已排序”,如果不是,則寫“用戶輸入未排序”。

到目前為止,這是我的代碼:

public static void Main()
{
    int[] array = new int[20];
    int n = 0;
    char Continue;

    InputArray(array, ref n);
    IsSorted(array, n);

    Console.WriteLine("{0}", IsSorted(array, n));

    do{


        Console.Write("Would you like to continue? Y/N : ");
        Continue = Convert.ToChar(Console.ReadLine());
        Continue = char.ToUpper(Continue);

      }while(Continue != 'N');

}

    public static void InputArray(int[] array, ref int n)
{
    int i = 0;

    Console.Write("Enter a number of elements under 20: ");
    n = Convert.ToInt32(Console.ReadLine());

    if (n < 0 || n > 20)
    {
        Console.Write("Please enter a number greater than zero and less than 20: ");
        n = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the {0} elements:", n);
        for (i = 0; i < n; ++i)
            array[i] = Convert.ToInt32(Console.ReadLine());
    }
    else
    {
        Console.WriteLine("Enter the {0} elements:", n);
        for (i = 0; i < n; ++i)
            array[i] = Convert.ToInt32(Console.ReadLine());
      }

}

   public static bool IsSorted(int[] array, int n)
{
    for (int i = 0; i < array.Length; i++)
        if (array[i] > array[i + 1])
        {
            return true;
        }
        return false;      
}

}

無論如何在這種情況下我都會保持真實...

只要滿足第一項和第二項的條件,您的方法就會返回true ,而不檢查所有其他元素。

public static bool IsSorted(int[] array, int n)
{
    for (int i = 1; i < array.Length; i++)
    {
        if (array[i - 1] > array[i])
        {
            return false;
        }
    }
    return true;
}

我做了兩個更改:

  1. 盡早返回false ,但要等到返回true為止,直到循環結束。
  2. 由於i + 1索引訪問,您的解決方案將拋出ArrayOutOfBoundException i = 1開始,轉到i < array.Lenght ,並在索引器中使用i - 1更容易。

嘗試使用LINQ運算符,如下所示:

public static bool IsSorted(int[] array, int n)
{
    return
        array
            .Skip(1)
            .Zip(array, (a1, a0) => a1 - a0)
            .All(a => a >= 0);  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM