Skip to content

Instantly share code, notes, and snippets.

@1AdAstra1
Forked from t-nissie/quicksort.f
Last active March 1, 2023 18:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 1AdAstra1/6f7785373efe5bb6c254d2e20c78ccc4 to your computer and use it in GitHub Desktop.
Save 1AdAstra1/6f7785373efe5bb6c254d2e20c78ccc4 to your computer and use it in GitHub Desktop.
quick sort in Fortran
! quicksort.f -*-f90-*-
! Author: t-nissie, some tweaks by 1AdAstra1
! License: GPLv3
! Gist: https://gist.github.com/t-nissie/479f0f16966925fa29ea
!!
recursive subroutine quicksort(a)
implicit none
real :: a(:)
real x, t
integer :: first = 1, last
integer i, j
last = size(a, 1)
x = a( (first+last) / 2 )
i = first
j = last
do
do while (a(i) < x)
i=i+1
end do
do while (x < a(j))
j=j-1
end do
if (i >= j) exit
t = a(i); a(i) = a(j); a(j) = t
i=i+1
j=j-1
end do
if (first < i - 1) call quicksort(a(first : i - 1))
if (j + 1 < last) call quicksort(a(j + 1 : last))
end subroutine quicksort
#-*-Makefile-*- for quicksort
##
## gfortran (GNU Fortran in GCC)
FC=gfortran
FFLAGS=-g -Wall -ffree-form -O2
### ifort (Intel Fortran)
#FC=ifort
#FFLAGS=-g -free -warn all
all: sortreal8
./$<
sortreal8: sortreal8.o quicksort.o
$(FC) $(FFLAGS) -o $@ $^
clean:
rm -f core *.o *.mod sortreal8
! sortreal8.f -*-f90-*-
! Author: t-nissie
!!
program sortreal8
implicit none
real :: a(10)
a( 1) = 1.0d0
a( 2) = 1.0d0
a( 3) = 5.0d0
a( 4) = 3.0d0
a( 5) = -1.0d0
a( 6) = 11.0d0
a( 7) = 1.0d1
a( 8) = 31.0d0
a( 9) = -5.0d0
a(10) = 1.1d0
call quicksort(a)
write(6,'(f10.5)') a
end program sortreal8
!Local variables:
! compile-command: "gfortran -g -Wall -ffree-form -O2 -c sortreal8.f && gfortran -g -Wall -ffree-form -O2 -c quicksort.f && gfortran -g -Wall -ffree-form -O2 -o sortreal8 sortreal8.o quicksort.o && ./sortreal8"
!End:
@zbeekman
Copy link

zbeekman commented Dec 5, 2018

👏

@timhdesilva
Copy link

This is great, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment