Skip to content

Instantly share code, notes, and snippets.

@t-nissie
Last active January 31, 2023 18:49
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save t-nissie/479f0f16966925fa29ea to your computer and use it in GitHub Desktop.
Save t-nissie/479f0f16966925fa29ea to your computer and use it in GitHub Desktop.
quick sort in Fortran
! quicksort.f -*-f90-*-
! Author: t-nissie
! License: GPLv3
! Gist: https://gist.github.com/t-nissie/479f0f16966925fa29ea
!!
recursive subroutine quicksort(a, first, last)
implicit none
real*8 a(*), x, t
integer first, last
integer i, j
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*8 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,1,10)
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:
@mishktu
Copy link

mishktu commented Jun 30, 2016

Thanks for nice code.

@b-fg
Copy link

b-fg commented Jul 25, 2017

Thank you, it has been useful.

@ansWenlong
Copy link

Thank you very much for the nice and clean code! It is very helpful.

@1AdAstra1
Copy link

I found this while doing my college homework... our instructor insists we use as much vectorization and array slicing as possible, and stay away from direct index passing... so, for people in similar conditions I made a vectorized (and arguably more concise, as the function requires less parameters now) version of this gist: https://gist.github.com/1AdAstra1/6f7785373efe5bb6c254d2e20c78ccc4 . If anyone else needs it - feel free to use it!

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