我试图找出用户输入的数组是否已排序(尽管不尝试排序).如果用户的输入是从最小到最大的升序,我想写一条消息说"输入已排序",如果不是"用户输入未排序".
到目前为止这是我的代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
无论在这种情况下是什么,我都会变得真实......
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;
}
Run Code Online (Sandbox Code Playgroud)
我做了两处改动:
false提前返回,但等待返回true直到达到循环结束.ArrayOutOfBoundException由于i + 1索引访问,您的解决方案将抛出.在索引器中开始i = 1,转到i < array.Lenght和使用起来更容易i - 1.