检查当前循环迭代是否大于前一个

Check if current loop iteration is greater than the previous one

我必须检查 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");

仅当 x[i] <= x[i + 1] 对于 i

的所有可能值时,数组才被排序

所以让我们开始假设它已排序。如果我们发现一对值 满足我们的条件,则数组不会排序。

bool isSorted = true;
for (int i = 0; i < arrayName.Length - 1; i++) {
    if (arrayName[i] > arrayName[i + 1]) {
        isSorted = false; 
        break; // One pair isn't sorted, so we don't need to check anything else
    }
}

既然你已经检查了你需要的一切,你可以输出了。

if (isSorted)
    Console.WriteLine("Array is sorted");
else
    Console.WriteLine("Not sorted");

从索引 1 开始迭代,然后您可以使用 arrayName[i - 1] 引用上一项。请注意,-1 必须应用于索引,而不是数组值 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");
}

哦,作业题。还不如找点乐子。这可以用 Enumerable 一般地完成

bool isSorted<T>(IEnumerable<T> a) where T : IComparable => Enumerable.Range(1, a.Count() - 1).All(i => a.ElementAt(i).CompareTo(a.ElementAt(i - 1)) >= 0);

调用它

int[] arrayName = { 1, 2, 3, 4, 5 }; //This one should be true
int[] arrayName2 = { 5, 4, 3, 6 }; //This one should be false
double[] arrayName3 = { 4, 4, 8, 11.5 }; //This one should be true
var arrayName4 = new Single[] { 3F, 4.5F, 6F, 1.0F }.ToList(); //This one should be false
var arrayName5 = new string[] { "a", "abb", "b", "c" }; //True
var arrayName6 = new string[] { "a", "a", "b", "a" }; //False

Console.WriteLine(isSorted(arrayName));
Console.WriteLine(isSorted(arrayName2));
Console.WriteLine(isSorted(arrayName3));
Console.WriteLine(isSorted(arrayName4));
Console.WriteLine(isSorted(arrayName5));
Console.WriteLine(isSorted(arrayName6));

True
False
True
False
True
False

通用且可重复使用。

还有

bool isSorted2<T>(IEnumerable<T> a) where T : IComparable => a.SequenceEqual(a.OrderBy(b => b));

这涉及到对内存中的数组进行排序,但看起来更整洁。