Fortran Recursive Merge Sort
program merge_sort_recursive_example implicit none ! Main program to demonstrate recursive merge sort integer, parameter :: array_size = 15 integer :: arr(array_size) integer :: i ! Initialize array with some values arr = [38, 27, 43, 3, 9, 82, 10, 15, 50, 6, 1, 77, 22, 31, 19] p...
This Fortran program implements the Merge Sort algorithm using recursion. Merge Sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts them, and then merges the two sorted...
The provided Fortran code implements a recursive Merge Sort algorithm. The `merge_sort` subroutine divides the array into two halves until the base case (an array segment of size 0 or 1) is reached. The `merge` subroutine then combines these sorted halves. It uses a temporary array to store the merged elements, comparing elements from both halves and placing the smaller one into the temporary array. After all elements are merged, they are copied back to the original array segment. The time complexity is O(n log n) for all cases (best, average, worst) because the array is always divided and merged. The space complexity is O(n) due to the temporary array used in the merge step. Edge cases like empty arrays and single-element arrays are handled by the base case of the recursion. The invariant for the `merge` subroutine is that when it begins, `a(low...mid)` and `a(mid+1...high)` are sorted, and when it finishes, `a(low...high)` is sorted. The recursive structure ensures that the entire array is eventually sorted.
PROGRAM merge_sort_recursive_example DECLARE integer array arr INITIALIZE arr with values PRINT original array CALL merge_sort(arr, 1, size(arr)) PRINT sorted array TEST with empty array TEST with single-element array TE...