|
1 |
| -!> Recursive Bubble Sort |
| 1 | +!> Recursive Bubble Sort Module |
2 | 2 | !!
|
3 |
| -!! This is a simple example for recursive bubble sort algorithm in Fortran. |
4 |
| - |
5 |
| -program recursive_bubble_sort_program |
6 |
| -implicit none |
7 |
| - |
8 |
| - real :: array(5) |
9 |
| - |
10 |
| - !! random_number subroutine fills the argument with random numbers. |
11 |
| - call random_number(array) |
12 |
| - |
13 |
| - print*, "Before:", array |
14 |
| - |
15 |
| - !! Bubble sort subroutine call. |
16 |
| - call recursive_bubble_sort(array, size(array)) |
17 |
| - |
18 |
| - print*, "After:", array |
| 3 | +!! This module contains a subroutine for sorting a collection using the recursive bubble sort algorithm. |
19 | 4 |
|
| 5 | +module recursive_bubble_sort_module |
| 6 | + implicit none |
20 | 7 | contains
|
21 | 8 |
|
22 | 9 | !! This subroutine sorts the collection recursively using bubble sort.
|
23 | 10 | !! Recursive keyword at the start declares that the function is recursive.
|
24 |
| - recursive subroutine recursive_bubble_sort(collection, collection_size) |
25 |
| - real, dimension(:), intent(inout) :: collection !! A collection for elements of type real |
| 11 | + recursive subroutine recursive_bubble_sort(collection, collection_size) |
| 12 | + real, dimension(:), intent(inout) :: collection !! A collection for elements of type real. |
26 | 13 | integer, intent(in) :: collection_size !! Collection's size.
|
27 | 14 |
|
28 | 15 | integer :: i
|
29 | 16 | real :: temp
|
30 | 17 |
|
31 |
| - do i = 1, collection_size |
32 |
| - if (collection(i) .gt. collection(i+1)) then |
33 |
| - !! If collection is out of order in [i, i+1] region, |
34 |
| - !! swap these values using a temp variable as follows. |
35 |
| - |
| 18 | + !! Perform bubble sort on the collection. |
| 19 | + do i = 1, collection_size - 1 |
| 20 | + if (collection(i) .gt. collection(i + 1)) then |
| 21 | + !! Swap values if they are out of order in [i, i + 1] region. |
36 | 22 | temp = collection(i)
|
37 |
| - collection(i) = collection(i+1) |
38 |
| - collection(i+1) = temp |
| 23 | + collection(i) = collection(i + 1) |
| 24 | + collection(i + 1) = temp |
39 | 25 | end if
|
40 | 26 | end do
|
41 | 27 |
|
| 28 | + !! Recursively call the subroutine with (collection_size - 1) if size > 2. |
42 | 29 | if (collection_size .gt. 2) then
|
43 |
| - !! If collection's size is greater then 2, |
44 |
| - !! this subroutine recursively calls itself with (collection_size - 1) for size argument. |
45 | 30 | call recursive_bubble_sort(collection, collection_size - 1)
|
46 | 31 | end if
|
47 | 32 |
|
48 | 33 | end subroutine recursive_bubble_sort
|
49 | 34 |
|
50 |
| -end program recursive_bubble_sort_program |
51 |
| - |
| 35 | +end module recursive_bubble_sort_module |
0 commit comments