Fortran,定义sort函数为数组降序排序

    subroutine sort(a,c,idx,n)
    implicit none
    integer n
    real*8 :: a(n),c(n),temp
    integer :: idx(n), i, j

    ! 初始化索引数组
    do i = 1, n
        idx(i) = i
    end do

    c = a
    ! 使用冒泡排序方法按降序排列
    do i = 1, n-1
        do j = 1, n-i
            if (c(j) < c(j+1)) then
                ! 交换元素
                temp = c(j)
                c(j) = c(j+1)
                c(j+1) = temp
                ! 交换索引
                temp = idx(j)
                idx(j) = idx(j+1)
                idx(j+1) = temp
            end if
        end do
    end do
    end subroutine sort

参数

a:要计算的数组

c:结果数组

idx:a(idx) = c

n:数组大小

结果和matlab的sort函数应该是一致的。

你可能感兴趣的:(算法)