Sorts an integer array ivec
in increasing order.
Uses a basic recursive quicksort
(with insertion sort for partitions with 20 elements).
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
integer, | intent(inout), | dimension(:) | :: | ivec |
subroutine sort_ascending(ivec) implicit none integer,dimension(:),intent(inout) :: ivec call quicksort(1,size(ivec)) contains recursive subroutine quicksort(ilow,ihigh) !! Sort the array implicit none integer,intent(in) :: ilow integer,intent(in) :: ihigh integer :: ipivot !! pivot element integer :: i !! counter integer :: j !! counter if ( ihigh-ilow<=max_size_for_insertion_sort .and. ihigh>ilow ) then ! do insertion sort: do i = ilow + 1,ihigh do j = i,ilow + 1,-1 if ( ivec(j) < ivec(j-1) ) then call swap(ivec(j),ivec(j-1)) else exit end if end do end do else if ( ihigh-ilow>max_size_for_insertion_sort ) then ! do the normal quicksort: call partition(ilow,ihigh,ipivot) call quicksort(ilow,ipivot - 1) call quicksort(ipivot + 1,ihigh) end if end subroutine quicksort subroutine partition(ilow,ihigh,ipivot) !! Partition the array, based on the !! lexical ivecing comparison. implicit none integer,intent(in) :: ilow integer,intent(in) :: ihigh integer,intent(out) :: ipivot integer :: i,ip call swap(ivec(ilow),ivec((ilow+ihigh)/2)) ip = ilow do i = ilow + 1, ihigh if ( ivec(i) < ivec(ilow) ) then ip = ip + 1 call swap(ivec(ip),ivec(i)) end if end do call swap(ivec(ilow),ivec(ip)) ipivot = ip end subroutine partition end subroutine sort_ascending