fortran - Fortran 二维数组的冒泡排序行
问题描述
我正在处理作业的第二部分,该部分要求我对矩阵进行重新排序,以使每一行都单调递增,并且每行的第一个元素单调递增。如果两行具有相同的初始值,则应按行中的第二个元素对行进行排序。如果它们都相同,它应该是第三个元素,继续到最后一个元素。
我写了一个冒泡排序,它适用于第一部分(重新排序每一行)。我为第二部分编写了冒泡排序(确保每行的第一个元素单调递增)。但是,我遇到了一个无限循环,我不明白为什么。
我确实理解问题是我的“inorder”变量最终没有设置为true(这将结束while循环)。但是,我不明白为什么 inorder 没有设置为 true。我的逻辑如下:一旦以下代码将行交换到所有行都按顺序排列的程度,我们将再通过一次 while 循环(并且 inorder 将设置为 true),这将导致 while 循环结束。我很困惑为什么这没有发生。
inorder = .false.
loopA: do while ( .not. inorder ) !While the rows are not ordered
inorder = .true.
loopB: do i = 1, rows-1 !Iterate through the first column of the array
if (arr(i,1)>arr(i+1,1)) then !If we find a row that is out of order
inorder = .false.
tempArr = arr(i+1,:) !Swap the corresponding rows
arr(i+1,:) = arr(i,:)
arr(i,:) = tempArr
end if
if (arr(i,1)==arr(i+1,1)) then !The first elements of the rows are the same
loopC: do j=2, cols !Iterate through the rest of the row to find the first element that is not the same
if (arr(i,j)>arr(i+1,j)) then !Found elements that are not the same and that are out of order
inorder = .false.
tempArr = arr(i+1,:) !Swap the corresponding rows
arr(i+1,:) = arr(i,:)
arr(i,:) = tempArr
end if
end do loopC
end if
end do loopB
end do loopA
示例输入:
6 3 9 23 80
7 54 78 87 87
83 5 67 8 23
102 1 67 54 34
78 3 45 67 28
14 33 24 34 9
示例(正确)输出(我的代码未生成):
1 34 54 67 102
3 6 9 23 80
3 28 45 67 78
5 8 23 67 83
7 54 78 87 87
9 14 24 33 34
盯着这个看几个小时也有可能让我错过了一些愚蠢的事情,所以我很感激任何指点。
解决方案
当您比较第一个元素相同的行时,您将遍历整个数组并比较每个项目。
因此,如果您有两个这样的数组:
1 5 3
1 2 4
那么第一个元素也是一样的,它进入你代码的第二部分。
排在第二位,5>2,所以它交换它:
1 2 4
1 5 3
但它并没有停止。第三位,4>3,所以它交换回来
1 5 3
1 2 4
现在你又回到了原来的位置。
干杯
推荐阅读
- database - 数据仓库:谁发起从多个源提取数据到暂存区,是源还是数据仓库?
- svelte - 如何让 sourcemaps 与 svelte-preprocess、typescript、sourced .ts 文件一起使用
- sql - 如何在postgreSQL中获取20个连续数字行
- javascript - 在画布上相对绘制线阵列
- python - 如何用python中另一行的值填充某行
- c# - C# 内存不足从 Dynamics 365 检索实体详细信息
- javascript - jquery 将相同的类与选择中的选项混淆
- python - 在 ResNet50 TFLIte 模型中使用修改后的权重执行卷积和激活
- oracle - 交互式报告过滤器文本未在 Oracle APEX 应用程序翻译中进行翻译
- excel - 共同创作时 Excel Power Query 刷新 - 无法合并更改