首页 > 解决方案 > 检查当前循环迭代是否大于前一个

问题描述

我必须检查一个 int 数组是否按升序排序,例如 1、2、3、4 等。

所以这是我在伪代码中的尝试:

int[] arrayName = {1,2,3,4,5};   // This should be true
int[] arrayName2 = {5,4,3,6};    // This should be false

for (int i = 0; i < arrayName.Length; i++) 
{
    if (arrayName[i] < arrayName[i] - 1)
    {
        Console.WriteLine("The array is sorted");
    }
    else 
        Console.WriteLine("The array is not sorted");
}

我的问题:他们是一种检查当前迭代与前一次迭代的方法吗?我也不能在这个练习中使用任何库或扩展,所以基本上我只能使用“系统”

例如:

if (currentIteration > previousIteration) 
    Console.WriteLine("The array is sorted");
else 
    Console.WriteLine("The array is not sorted");

标签: c#arraysloopsinteger

解决方案


从索引 1 开始迭代,然后您可以使用arrayName[i - 1]. 请注意,-1必须将 应用于索引,而不是数组 value arrayName[i] - 1

此外,您希望在测试数组后打印结果,而不是在每次迭代时打印。最好创建一个函数,以便您可以轻松地将其应用于多个数组。

static bool IsArraySorted(int[] a)
{
    for (int i = 1; i < a.Length; i++) {
        if (a[i] < a[i - 1]) {
            return false; // We don't need to test the rest of the array.
        }
    }
    return true;
}

现在,您可以像这样使用它

if (IsArraySorted(arrayName)) {
    Console.WriteLine("The array is sorted");
} else {
    Console.WriteLine("The array is not sorted");
}

推荐阅读