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



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

我的问题是:它们是一种检查当前迭代与前一次迭代的方法吗?我不能使用任何库或扩展来进行这个练习,所以基本上我只能使用"System">

例如:

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

正确的




通用且可重用。

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

需要在内存中对数组进行排序,但看起来更整洁。

最新更新