我正在做一个赋值的第二部分,它要求我重新排序一个矩阵,使得每一行都是单调递增的,并且每行的第一个元素是单调递增的。如果两行具有相同的初始值,则应按行中的第二个元素对行进行排序。如果这两个元素相同,则它应该是第三个元素,继续到最后一个元素。
我已经编写了一个冒泡排序,可以很好地用于第一部分(重新排序每一行)。我已经为第二部分编写了一个冒泡排序(确保每行的第一个元素是单调递增的)。然而,我遇到了一个无限循环,我不明白为什么。
我确实理解这个问题是我的"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盯着这个看了几个小时也有可能让我错过了一些愚蠢的东西,所以我很感谢大家的指点。
发布于 2019-04-15 08:48:29
当您比较第一个元素相同的行时,然后遍历整个数组并比较每个单独的项。
所以如果你有两个这样的数组:
1 5 3
1 2 4那么第一个元素是相同的,它进入代码的第二部分。
排在第二位的是5>2,所以它交换了它:
1 2 4
1 5 3但之后它就不会停止。在第三位,4>3,所以它把它换回来
1 5 3
1 2 4现在你又回到了原来的地方。
干杯
https://stackoverflow.com/questions/55678899
复制相似问题