c# - 检查当前循环迭代是否大于前一个
问题描述
我必须检查一个 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");
解决方案
从索引 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");
}
推荐阅读
- ios - 使用代码快速堆栈视图隐藏和显示不起作用
- sql-server - 如果您想要一个或另一个并且它们不相关,是否可以在同一个查询中同时使用 Where 和 Have ?
- javascript - 将元素的旋转重置回原始状态(rotatable.js + jquery UI)?
- python - 问题在 Raspberry Pi 上获取 PHP 脚本以执行转动电机的 Python 脚本
- java - 如何从 Android Studio 中的 Webview 加载的 Url 中删除段落标签?
- python - Python 3.8 - BeautifulSoup 4 - unwrap() 不会删除所有标签
- android - Circular Reveal 动画 onTouch Android
- php - PHP根据货币收入和结果SQL计算总现金
- git - 在由 git hooks 修改的文件上使用 skip-worktree?
- excel - “对象'范围'的方法'值'失败”错误的问题