首页 > 解决方案 > 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

盯着这个看几个小时也有可能让我错过了一些愚蠢的事情,所以我很感激任何指点。

标签: fortran

解决方案


当您比较第一个元素相同的行时,您将遍历整个数组并比较每个项目。

因此,如果您有两个这样的数组:

1 5 3
1 2 4

那么第一个元素也是一样的,它进入你代码的第二部分。

排在第二位,5>2,所以它交换它:

1 2 4
1 5 3

但它并没有停止。第三位,4>3,所以它交换回来

1 5 3
1 2 4

现在你又回到了原来的位置。

干杯


推荐阅读