algorithm - 在嵌套 for 循环中使用 j= i+1 vs j = 1?

标签 algorithm pseudocode

我很难回答这个问题。所以我就用一个例子来说明。

假设我有以下数组:A = {5,8,1,3,2,6},大小为 n = 6,索引为 A[0...5]。

我想运行某种扫描,以便在从左到右的遍历中将每个值与其相邻的值进行比较。以下 2 个运行嵌套 for 循环的代码片段有什么区别?

// snippet 1, using i to take the first and j to take whatever is next to i.
for i <- 0 to n-2 do
    for j <- i+1 to n-1 do
       // do the scanning, comparing, etc.... 


//snippet 2 using i to take the first and j to take the second. 
for i <- 0 to n-2 do
        for j <- 1 to n-1 do
           // do the scanning, comparing, etc.... 

我认为它们完全相同,并且在我所做的笔/纸测试中找不到任何差异。有吗?

最佳答案

在第一个中,ji的下一个值开始计数。

示例:i = 1, j = 2 | i = 2, j = 3

在第二个中,无论 i 的值如何,您都将从 1 开始计数。换句话说,变量 i 对变量 j 没有影响。

两者都有各自的用途,但这完全取决于您如何使用它们来获取数组元素。

关于algorithm - 在嵌套 for 循环中使用 j= i+1 vs j = 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40897769/

相关文章:

algorithm - 有一个 int I 和 number if iterations 和一个函数 DrawPoint(x,y) 如何画一个圆?

algorithm - 如何检测是否存在重复模式

algorithm - 我将如何着手编写伪代码以在邻接矩阵中查找汇?

algorithm - 编程代数方程

algorithm - 没有Endgame Tablebases的国际象棋残局引擎的实现

c# - LINQ 是否有任何简单/优雅的方法来获取第一个元素并将其放在最后?

sql - 使用用户名列而不是 id?

algorithm - 在时间范围列表中查找(数量)重叠

javascript - 找出 4 个百分比之间的所有可能性

python - 在 Python 中使用 Networkx 从 DAG 中查找最长的加权路径?