Quoted from JohnCampbell
I have done some testing of 85 million values on 2.8ghz i5.
If the numbers are only slightly out of sequence:
do i = 1,n
call random_number(real_array(i))
real_array(i) = real_array(i) + real(i)*0.125
end do
This results in quick sort of 4 seconds, while bubble sort of 2 seconds. (shell takes 4 seconds also)
For such inputs with mild disorder, if the data set consists of a sequence of blocks, with disorder only within blocks but such that every element of block k +1 is larger than every element of block k, insertion sort is a good choice. Oddly, you did not include this algorithm in your repertoire in the test program. Try the following program, please.
program tinssrt
! test insertion sort
implicit none
integer :: i, N, ktr
double precision, allocatable :: A(:)
integer, allocatable :: idx(:)
real :: t1,t2
!
N=10000000 ! start with N = 10 million
do ktr = 1,4
allocate(A(N),idx(N))
call random_number(A)
idx=(/ (i,i=1,N) /)
A=A+idx*0.125d0 ! (random real between 0 and 1) + (1:N)*0.125
if (N <= 100) print '(' Unsorted:',/,(10F8.4))',A
call cpu_time(t1)
call inssort(N,idx,A)
call cpu_time(t2)
if (N <= 100) then
print '(' Sorted: ',/,(10F8.4))',A
print '(20I4)',idx
end if
deallocate(A,idx)
print 10,N,t2-t1
10 format(1x,i10,2x,F7.3)
N = N*2 ! double N
end do
end program
subroutine inssort(N,idx,A)
implicit none
integer, intent(in) :: N
integer, intent(in out) :: idx(N)
double precision, intent(in) :: A(N)
integer :: i,j,itmp
!
do i = 2, N
j = i-1
do while (j > 0)
if (A(idx(j)) < A(idx(j+1))) exit
itmp = idx(j+1)
idx(j+1) = idx(j)
idx(j) = itmp
j = j - 1
end do
end do
return
end subroutine inssort
On a laptop with a i7-2720QM CPU, this program took about 1 second for N = 80 million.
If the values are random ( call random_number(real_array) ) my quick sort takes about 50 seconds. My bubble and shell sorts are still running after 2 hours 50 minutes !!
Many algorithms (Quicksort, Mergesort, etc.) perform better when they are augmented by incorporating a switch to insertion sort for small partitions.
The sort routines of the standard libraries of C++, Java, C# and Python use such hybrid algorithms. For example, Google Search with 'standard sort algorithm in .net'.