|
本帖最后由 SolaProject 于 2021-6-9 01:44 编辑
如果只是要求输出位置,而非指向其地址的索引,创建一个和排序数组结构大小相同的数组,然后按照单个排序的维度进行从1到n的递增赋值,对原数组排序的同时,对新创建的数组执行相同的操作即可,如下:
[Fortran] 纯文本查看 复制代码 program example
implicit none
integer, dimension(2, 3) :: a=reshape((/4, 9, 6, 7, 5, 3/), (/2, 3/))
integer, dimension(:, :), allocatable :: aLoc
integer :: temp
integer :: minLoc
integer :: errorLevel
integer :: i, j, k
allocate(aLoc, source=a, stat=errorLevel)
if ( errorLevel /= 0 ) stop ""
do i = 1, size(a, 1)
do j = 1, size(a, 2)
aLoc(i, j) = j
end do
end do
write(*, '(A,/(I1, ",", I1, ",", I1))') '输入矩阵:', ((a(i, j), j = 1, size(a, 2)), i = 1, size(a, 1))
write(*, '(A,/(I1, ",", I1, ",", I1))') '序号矩阵:', ((aLoc(i, j), j = 1, size(a, 2)), i = 1, size(a, 1))
do i = 1, size(a, 1)
do j = 1, size(a, 2)
minLoc = j
do k = j+1, size(a, 2)
if ( a(i, minLoc) > a(i, k) ) then
minLoc = k
end if
end do
if ( k /= j ) then
temp = a(i, minLoc)
a(i, minLoc) = a(i, j)
a(i, j) = temp
temp = aLoc(i, minLoc)
aLoc(i, minLoc) = aLoc(i, j)
aLoc(i, j) = temp
end if
end do
end do
write(*, '(A,/(I1, ",", I1, ",", I1))') '输入矩阵按行排序后:', ((a(i, j), j = 1, size(a, 2)), i = 1, size(a, 1))
write(*, '(A,/(I1, ",", I1, ",", I1))') '序号矩阵排序对应值:', ((aLoc(i, j), j = 1, size(a, 2)), i = 1, size(a, 1))
deallocate(aLoc, stat=errorLevel)
if ( errorLevel /= 0 ) stop ""
end program example 输出结果:
输入矩阵:
4,6,5
9,7,3
序号矩阵:
1,2,3
1,2,3
输入矩阵按行排序后:
4,5,6
3,7,9
序号矩阵排序对应值:
1,3,2
3,2,1
如果需要指向地址的索引,创建一个包含指针的派生数据类型数组,然后执行类似操作即可。
|
|