1414
1515 implicit none
1616
17+ type searched_and_ordered_t
18+ integer , allocatable , dimension (:) :: s, o
19+ end type
20+
1721contains
1822
1923 module procedure construct_from_components
@@ -30,47 +34,52 @@ pure module function topological_sort(dag) result(order)
3034 call assert(all (dag% vertices(:)% edges_allocated()), " dag_s topological_sort: all(dag%vertices(:)%edges_allocated())" )
3135
3236 block
33- integer , allocatable :: discovered(:), searched(:)
37+ type (searched_and_ordered_t) searched_and_ordered
38+ integer , allocatable :: discovered(:)
3439 integer v
3540
36- allocate (discovered(0 ), order (0 ), searched (0 ))
41+ allocate (discovered(0 ), searched_and_ordered % o (0 ), searched_and_ordered % s (0 ))
3742
3843 do v = 1 , size (dag% vertices)
39- if (.not. any (v == searched )) then
40- call depth_first_search(v, [integer :: ], searched, order )
41- discovered = [discovered, searched ]
42- searched = discovered
44+ if (.not. any (v == searched_and_ordered % s )) then
45+ call depth_first_search(v, [integer :: ], searched_and_ordered % o, searched_and_ordered % s )
46+ discovered = [discovered, searched_and_ordered % s ]
47+ searched_and_ordered % s = discovered
4348 end if
4449 end do
50+ order = searched_and_ordered% o
4551 end block
4652
4753 contains
4854
49- pure recursive subroutine depth_first_search(v, d, s, o )
55+ pure recursive subroutine depth_first_search(v, d, o, s )
5056 integer , intent (in ) :: v, d(:)
5157 integer , intent (out ), allocatable :: s(:)
5258 integer , intent (inout ), allocatable :: o(:)
5359
5460 call assert(.not. any (v == d), " depth_first_search: cycle detected" , intrinsic_array_t([v,d]))
5561
5662 block
57- integer , allocatable :: dependencies(:), s_local(:), d_local(:)
63+ integer , allocatable :: dependencies(:), d_local(:)
5864 integer w
65+ type (searched_and_ordered_t) hybrid
5966
67+ hybrid% o = o
6068 dependencies = dag% depends_on(v)
6169
62- allocate (s_local (0 ), d_local (0 ))
70+ allocate (d_local (0 ), hybrid % s (0 ))
6371
6472 do w = 1 , size (dependencies)
65- if (.not. any (dependencies(w) == s_local )) then
66- call depth_first_search(dependencies(w), [d, v], s_local, o )
67- d_local = [d_local, s_local ]
68- s_local = d_local
73+ if (.not. any (dependencies(w) == hybrid % s )) then
74+ call depth_first_search(dependencies(w), [d, v], hybrid % o, hybrid % s )
75+ d_local = [d_local, hybrid % s ]
76+ hybrid % s = d_local
6977 end if
7078 end do
7179
72- if (.not. any (v == o)) o = [v, o]
73- s = [v, s_local]
80+ if (.not. any (v == hybrid% o)) hybrid% o = [v, hybrid% o]
81+ s = [v, hybrid% s]
82+ o = hybrid% o
7483 end block
7584
7685 end subroutine
0 commit comments