arrays - 这是想告诉我什么?

标签 arrays algorithm sorting loops termination

我正在读 RG Dromey 的书《如何用计算机解决它》。我被困在试图解释循环终止的句子中。问题来了:

Suppose we wish to establish that an array of n elements is in strictly ascending order (i.e. a[1] < a[2] < ... < a[n]) . To do this we can use the following instructions:

a[n+1] := a[n];
i := 1;
while a[i] < a[i+1] do i := i+1

(现在,如果 n 是元素的数量,那么 i 在这种情况下代表什么?它代表值吗?)

If n was assigned the value 5 and the data set was 2, 3, 5, 11, 14, then the first assignment prior to the loop would result in the array configuration below:

(这是我感到困惑的地方。)

a[1]  a[2]  a[3]  a[4]  a[5]  a[6]
2     3     5     11    14    14

The two 14's guarantee that the test a[i] < a[i+1] will be false when i = n and so the loop will terminate correctly when i = n if not before.

(这很令人困惑。)

最佳答案

i 只是索引
我:= 1;表示 i 等于 1
i := i+1 表示 i 加 1

n = 5

a[5] = 14
a[5+1] = a[6] = 14

14 < 14 为 false - 循环终止

关于arrays - 这是想告诉我什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827173/

相关文章:

sorting - Symfony表单实体/文档对属性进行排序

c - 如何找到数组中最短运行的最后一个索引?

java - 从我创建的类创建对象数组

c++ - 如何用一维数组列表初始化二维数组?

arrays - 如何查找其特定字段不是数组类型的文档?

java - 这个 Stacked Number 生成代码有什么问题?

javascript - 根据另一个不同长度数组中的值对数组进行排序

java - 从 Arrays.asList() 中排序列表也会更改原始数组吗?

c# - 将大量项目映射到较小的位置标记集

c++ - remove_if 有问题(删除几次后停止删除)