声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 1989|回复: 0

[Fortran] Fortran 快速排序算法

[复制链接]
发表于 2015-11-3 17:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
快速排序(Quicksort)是对冒泡排序的一种改进。此段代码实现了Fortran快速排序算法。 Visual Fortran 提供的 QSort 函数内部即采用此算法。
20140208073140548.jpg
  1. ! Recursive Fortran 95 quicksort routine
  2. ! sorts real numbers into ascending numerical order
  3. ! Author: Juli Rew, SCD Consulting (juliana@ucar.edu), 9/03
  4. ! Based on algorithm from Cormen et al., Introduction to Algorithms,
  5. ! 1997 printing
  6. ! Made F conformant by Walt Brainerd
  7. module qsort_c_module
  8.   implicit none
  9.   public :: QsortC
  10.   private :: Partition

  11. contains

  12.   recursive subroutine QsortC(A)
  13.     real, intent(in out), dimension(:) :: A
  14.     integer :: iq
  15.     if(size(A) > 1) then
  16.       call Partition(A, iq)
  17.       call QsortC(A(:iq-1))
  18.       call QsortC(A(iq:))
  19.     endif
  20.   end subroutine QsortC

  21.   subroutine Partition(A, marker)
  22.     real, intent(in out), dimension(:) :: A
  23.     integer, intent(out) :: marker
  24.     integer :: i, j
  25.     real :: temp
  26.     real :: x      ! pivot point
  27.     x = A(1)
  28.     i= 0
  29.     j= size(A) + 1
  30.     do
  31.       j = j-1
  32.       do
  33.         if (A(j) <= x) exit
  34.         j = j-1
  35.       end do
  36.       i = i+1
  37.       do
  38.         if (A(i) >= x) exit
  39.         i = i+1
  40.       end do
  41.       if (i < j) then
  42.         ! exchange A(i) and A(j)
  43.         temp = A(i)
  44.         A(i) = A(j)
  45.         A(j) = temp
  46.       elseif (i == j) then
  47.         marker = i+1
  48.         return
  49.       else
  50.         marker = i
  51.         return
  52.       endif
  53.     end do
  54.   end subroutine Partition

  55. end module qsort_c_module

  56. program www_fcode_cn
  57.   use qsort_c_module
  58.   implicit none
  59.   integer, parameter :: r = 10
  60.   real, dimension(1:r) :: myarray = (/0, 50, 20, 25, 90, 10, 5, 1, 99, 75/)
  61.   print *, "原数组:", myarray
  62.   call QsortC(myarray)
  63.   print *, "排序后:", myarray
  64. end program www_fcode_cn
复制代码
回复
分享到:

使用道具 举报

您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-4-19 08:43 , Processed in 0.057780 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表