forked from fortran-lang/stdlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstdlib_sorting_ord_sort.fypp
790 lines (668 loc) · 30.3 KB
/
stdlib_sorting_ord_sort.fypp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
#:include "common.fypp"
#:set IRS_KINDS_TYPES = INT_KINDS_TYPES + REAL_KINDS_TYPES + STRING_KINDS_TYPES
#:set SIGN_NAME = ["increase", "decrease"]
#:set SIGN_TYPE = [">", "<"]
#:set SIGN_OPP_TYPE = ["<", ">"]
#:set SIGN_NAME_TYPE = list(zip(SIGN_NAME, SIGN_TYPE, SIGN_OPP_TYPE))
!! Licensing:
!!
!! This file is subjec† both to the Fortran Standard Library license, and
!! to additional licensing requirements as it contains translations of
!! other software.
!!
!! The Fortran Standard Library, including this file, is distributed under
!! the MIT license that should be included with the library's distribution.
!!
!! Copyright (c) 2021 Fortran stdlib developers
!!
!! Permission is hereby granted, free of charge, to any person obtaining a
!! copy of this software and associated documentation files (the
!! "Software"), to deal in the Software without restriction, including
!! without limitation the rights to use, copy, modify, merge, publish,
!! distribute, sublicense, and/or sellcopies of the Software, and to permit
!! persons to whom the Software is furnished to do so, subject to the
!! following conditions:
!!
!! The above copyright notice and this permission notice shall be included
!! in all copies or substantial portions of the Software.
!!
!! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
!! OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
!! MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
!! IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
!! CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
!! TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
!! SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
!!
!! The generic subroutine, `ORD_SORT`, is substantially a translation to
!! Fortran 2008 of the `"Rust" sort` sorting routines in
!! [`slice.rs`](https://github.com/rust-lang/rust/blob/90eb44a5897c39e3dff9c7e48e3973671dcd9496/src/liballoc/slice.rs)
!! The `rust sort` implementation is distributed with the header:
!!
!! Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
!! file at the top-level directory of this distribution and at
!! http://rust-lang.org/COPYRIGHT.
!!
!! Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
!! http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
!! <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
!! option. This file may not be copied, modified, or distributed
!! except according to those terms.
!!
!! so the license for the original`slice.rs` code is compatible with the use
!! of modified versions of the code in the Fortran Standard Library under
!! the MIT license.
submodule(stdlib_sorting) stdlib_sorting_ord_sort
implicit none
contains
#:for k1, t1 in IRS_KINDS_TYPES
module subroutine ${k1}$_ord_sort( array, work, reverse )
${t1}$, intent(inout) :: array(0:)
${t1}$, intent(out), optional :: work(0:)
logical, intent(in), optional :: reverse
logical :: reverse_
reverse_ = .false.
if(present(reverse)) reverse_ = reverse
if (reverse_) then
call ${k1}$_decrease_ord_sort(array, work)
else
call ${k1}$_increase_ord_sort(array, work)
endif
end subroutine ${k1}$_ord_sort
#:endfor
#:for sname, signt, signoppt in SIGN_NAME_TYPE
#:for k1, t1 in IRS_KINDS_TYPES
subroutine ${k1}$_${sname}$_ord_sort( array, work )
! A translation to Fortran 2008, of the `"Rust" sort` algorithm found in
! `slice.rs`
! https://github.com/rust-lang/rust/blob/90eb44a5897c39e3dff9c7e48e3973671dcd9496/src/liballoc/slice.rs#L2159
! The Rust version in turn is a simplification of the Timsort algorithm
! described in
! https://svn.python.org/projects/python/trunk/Objects/listsort.txt, as
! it drops both the use of 'galloping' to identify bounds of regions to be
! sorted and the estimation of the optimal `run size`. However it remains
! a hybrid sorting algorithm combining an iterative Merge sort controlled
! by a stack of `RUNS` identified by regions of uniformly decreasing or
! non-decreasing sequences that may be expanded to a minimum run size and
! initially processed by an insertion sort.
!
! Note the Fortran implementation simplifies the logic as it only has to
! deal with Fortran arrays of intrinsic types and not the full generality
! of Rust's arrays and lists for arbitrary types. It also adds the
! estimation of the optimal `run size` as suggested in Tim Peters'
! original `listsort.txt`, and an optional `work` array to be used as
! scratch memory.
${t1}$, intent(inout) :: array(0:)
${t1}$, intent(out), optional :: work(0:)
${t1}$, allocatable :: buf(:)
integer(int_size) :: array_size
integer :: stat
array_size = size( array, kind=int_size )
if ( present(work) ) then
if ( size( work, kind=int_size) < array_size/2 ) then
error stop "${k1}$_${sname}$_ord_sort: work array is too small."
endif
! Use the work array as scratch memory
call merge_sort( array, work )
else
! Allocate a buffer to use as scratch memory.
allocate( buf(0:array_size/2-1), stat=stat )
if ( stat /= 0 ) error stop "${k1}$_${sname}$_ord_sort: Allocation of buffer failed."
call merge_sort( array, buf )
end if
contains
pure function calc_min_run( n ) result(min_run)
!! Returns the minimum length of a run from 32-63 so that N/MIN_RUN is
!! less than or equal to a power of two. See
!! https://svn.python.org/projects/python/trunk/Objects/listsort.txt
integer(int_size) :: min_run
integer(int_size), intent(in) :: n
integer(int_size) :: num, r
num = n
r = 0_int_size
do while( num >= 64 )
r = ior( r, iand(num, 1_int_size) )
num = ishft(num, -1_int_size)
end do
min_run = num + r
end function calc_min_run
pure subroutine insertion_sort( array )
! Sorts `ARRAY` using an insertion sort.
${t1}$, intent(inout) :: array(0:)
integer(int_size) :: i, j
${t1}$ :: key
do j=1, size(array, kind=int_size)-1
key = array(j)
i = j - 1
do while( i >= 0 )
if ( array(i) ${signoppt}$= key ) exit
array(i+1) = array(i)
i = i - 1
end do
array(i+1) = key
end do
end subroutine insertion_sort
pure function collapse( runs ) result ( r )
! Examine the stack of runs waiting to be merged, identifying adjacent runs
! to be merged until the stack invariants are restablished:
!
! 1. len(-3) > len(-2) + len(-1)
! 2. len(-2) > len(-1)
integer(int_size) :: r
type(run_type), intent(in), target :: runs(0:)
integer(int_size) :: n
logical :: test
n = size(runs, kind=int_size)
test = .false.
if (n >= 2) then
if ( runs( n-1 ) % base == 0 .or. &
runs( n-2 ) % len <= runs(n-1) % len ) then
test = .true.
else if ( n >= 3 ) then ! X exists
if ( runs(n-3) % len <= &
runs(n-2) % len + runs(n-1) % len ) then
test = .true.
! |X| <= |Y| + |Z| => will need to merge due to rho1 or rho2
else if( n >= 4 ) then
if ( runs(n-4) % len <= &
runs(n-3) % len + runs(n-2) % len ) then
test = .true.
! |W| <= |X| + |Y| => will need to merge due to rho1 or rho3
end if
end if
end if
end if
if ( test ) then
! By default merge Y & Z, rho2 or rho3
if ( n >= 3 ) then
if ( runs(n-3) % len < runs(n-1) % len ) then
r = n - 3
! |X| < |Z| => merge X & Y, rho1
return
end if
end if
r = n - 2
! |Y| <= |Z| => merge Y & Z, rho4
return
else
r = -1
end if
end function collapse
pure subroutine insert_head( array )
! Inserts `array(0)` into the pre-sorted sequence `array(1:)` so that the
! whole `array(0:)` becomes sorted, copying the first element into
! a temporary variable, iterating until the right place for it is found.
! copying every traversed element into the slot preceding it, and finally,
! copying data from the temporary variable into the resulting hole.
${t1}$, intent(inout) :: array(0:)
${t1}$ :: tmp
integer(int_size) :: i
tmp = array(0)
find_hole: do i=1, size(array, kind=int_size)-1
if ( array(i) ${signt}$= tmp ) exit find_hole
array(i-1) = array(i)
end do find_hole
array(i-1) = tmp
end subroutine insert_head
subroutine merge_sort( array, buf )
! The Rust merge sort borrows some (but not all) of the ideas from TimSort,
! which is described in detail at
! (http://svn.python.org/projects/python/trunk/Objects/listsort.txt).
!
! The algorithm identifies strictly descending and non-descending
! subsequences, which are called natural runs. Where these runs are less
! than a minimum run size they are padded by adding additional samples
! using an insertion sort. The merge process is driven by a stack of
! pending unmerged runs. Each newly found run is pushed onto the stack,
! and then pairs of adjacentd runs are merged until these two invariants
! are satisfied:
!
! 1. for every `i` in `1..size(runs)-1`: `runs(i - 1)%len > runs(i)%len`
! 2. for every `i` in `2..size(runs)-1`: `runs(i - 2)%len >
! runs(i - 1)%len + runs(i)%len`
!
! The invariants ensure that the total running time is `O(n log n)`
! worst-case.
${t1}$, intent(inout) :: array(0:)
${t1}$, intent(inout) :: buf(0:)
integer(int_size) :: array_size, finish, min_run, r, r_count, &
start
type(run_type) :: runs(0:max_merge_stack-1), left, right
array_size = size(array, kind=int_size)
! Very short runs are extended using insertion sort to span at least
! min_run elements. Slices of up to this length are sorted using insertion
! sort.
min_run = calc_min_run( array_size )
if ( array_size <= min_run ) then
if ( array_size >= 2 ) call insertion_sort( array )
return
end if
! Following Rust sort, natural runs in `array` are identified by traversing
! it backwards. By traversing it backward, merges more often go in the
! opposite direction (forwards). According to developers of Rust sort,
! merging forwards is slightly faster than merging backwards. Therefore
! identifying runs by traversing backwards should improve performance.
r_count = 0
finish = array_size - 1
do while ( finish >= 0 )
! Find the next natural run, and reverse it if it's strictly descending.
start = finish
if ( start > 0 ) then
start = start - 1
if ( array(start+1) ${signoppt}$ array(start) ) then
Descending: do while ( start > 0 )
if ( array(start) ${signt}$= array(start-1) ) &
exit Descending
start = start - 1
end do Descending
call reverse_segment( array(start:finish) )
else
Ascending: do while( start > 0 )
if ( array(start) ${signoppt}$ array(start-1) ) exit Ascending
start = start - 1
end do Ascending
end if
end if
! If the run is too short insert some more elements using an insertion sort.
Insert: do while ( start > 0 )
if ( finish - start >= min_run - 1 ) exit Insert
start = start - 1
call insert_head( array(start:finish) )
end do Insert
if ( start == 0 .and. finish == array_size - 1 ) return
runs(r_count) = run_type( base = start, &
len = finish - start + 1 )
finish = start-1
r_count = r_count + 1
! Determine whether pairs of adjacent runs need to be merged to satisfy
! the invariants, and, if so, merge them.
Merge_loop: do
r = collapse( runs(0:r_count - 1) )
if ( r < 0 .or. r_count <= 1 ) exit Merge_loop
left = runs( r + 1 )
right = runs( r )
call merge( array( left % base: &
right % base + right % len - 1 ), &
left % len, buf )
runs(r) = run_type( base = left % base, &
len = left % len + right % len )
if ( r == r_count - 3 ) runs(r+1) = runs(r+2)
r_count = r_count - 1
end do Merge_loop
end do
if ( r_count /= 1 ) &
error stop "MERGE_SORT completed without RUN COUNT == 1."
end subroutine merge_sort
pure subroutine merge( array, mid, buf )
! Merges the two non-decreasing runs `ARRAY(0:MID-1)` and `ARRAY(MID:)`
! using `BUF` as temporary storage, and stores the merged runs into
! `ARRAY(0:)`. `MID` must be > 0, and < `SIZE(ARRAY)-1`. Buffer `BUF`
! must be long enough to hold the shorter of the two runs.
${t1}$, intent(inout) :: array(0:)
integer(int_size), intent(in) :: mid
${t1}$, intent(inout) :: buf(0:)
integer(int_size) :: array_len, i, j, k
array_len = size(array, kind=int_size)
! Merge first copies the shorter run into `buf`. Then, depending on which
! run was shorter, it traces the copied run and the longer run forwards
! (or backwards), comparing their next unprocessed elements and then
! copying the lesser (or greater) one into `array`.
if ( mid <= array_len - mid ) then ! The left run is shorter.
buf(0:mid-1) = array(0:mid-1)
i = 0
j = mid
merge_lower: do k = 0, array_len-1
if ( buf(i) ${signoppt}$= array(j) ) then
array(k) = buf(i)
i = i + 1
if ( i >= mid ) exit merge_lower
else
array(k) = array(j)
j = j + 1
if ( j >= array_len ) then
array(k+1:) = buf(i:mid-1)
exit merge_lower
end if
end if
end do merge_lower
else ! The right run is shorter ! check that it is stable
buf(0:array_len-mid-1) = array(mid:array_len-1)
i = mid - 1
j = array_len - mid -1
merge_upper: do k = array_len-1, 0, -1
if ( buf(j) ${signt}$= array(i) ) then
array(k) = buf(j)
j = j - 1
if ( j < 0 ) exit merge_upper
else
array(k) = array(i)
i = i - 1
if ( i < 0 ) then
array(0:k-1) = buf(0:j)
exit merge_upper
end if
end if
end do merge_upper
end if
end subroutine merge
pure subroutine reverse_segment( array )
! Reverse a segment of an array in place
${t1}$, intent(inout) :: array(0:)
integer(int_size) :: lo, hi
${t1}$ :: temp
lo = 0
hi = size( array, kind=int_size ) - 1
do while( lo < hi )
temp = array(lo)
array(lo) = array(hi)
array(hi) = temp
lo = lo + 1
hi = hi - 1
end do
end subroutine reverse_segment
end subroutine ${k1}$_${sname}$_ord_sort
#:endfor
#:endfor
module subroutine char_ord_sort( array, work, reverse )
character(len=*), intent(inout) :: array(0:)
character(len=len(array)), intent(out), optional :: work(0:)
logical, intent(in), optional :: reverse
logical :: reverse_
reverse_ = .false.
if(present(reverse)) reverse_ = reverse
if (reverse_) then
call char_decrease_ord_sort(array, work)
else
call char_increase_ord_sort(array, work)
endif
end subroutine char_ord_sort
#:for sname, signt, signoppt in SIGN_NAME_TYPE
subroutine char_${sname}$_ord_sort( array, work )
! A translation to Fortran 2008, of the `"Rust" sort` algorithm found in
! `slice.rs`
! https://github.com/rust-lang/rust/blob/90eb44a5897c39e3dff9c7e48e3973671dcd9496/src/liballoc/slice.rs#L2159
! The Rust version in turn is a simplification of the Timsort algorithm
! described in
! https://svn.python.org/projects/python/trunk/Objects/listsort.txt, as
! it drops both the use of 'galloping' to identify bounds of regions to be
! sorted and the estimation of the optimal `run size`. However it remains
! a hybrid sorting algorithm combining an iterative Merge sort controlled
! by a stack of `RUNS` identified by regions of uniformly decreasing or
! non-decreasing sequences that may be expanded to a minimum run size and
! initially processed by an insertion sort.
!
! Note the Fortran implementation simplifies the logic as it only has to
! deal with Fortran arrays of intrinsic types and not the full generality
! of Rust's arrays and lists for arbitrary types. It also adds the
! estimation of the optimal `run size` as suggested in Tim Peters'
! original `listsort.txt`, and an optional `work` array to be used as
! scratch memory.
character(len=*), intent(inout) :: array(0:)
character(len=len(array)), intent(out), optional :: work(0:)
character(len=:), allocatable :: buf(:)
integer(int_size) :: array_size
integer :: stat
if ( present(work) ) then
! Use the work array as scratch memory
call merge_sort( array, work )
else
! Allocate a buffer to use as scratch memory.
array_size = size( array, kind=int_size )
allocate( character(len=len(array)) :: buf(0:array_size/2-1), &
stat=stat )
if ( stat /= 0 ) error stop "${k1}$_${sname}$_ord_sort: Allocation of buffer failed."
call merge_sort( array, buf )
end if
contains
pure function calc_min_run( n ) result(min_run)
!! Returns the minimum length of a run from 32-63 so that N/MIN_RUN is
!! less than or equal to a power of two. See
!! https://svn.python.org/projects/python/trunk/Objects/listsort.txt
integer(int_size) :: min_run
integer(int_size), intent(in) :: n
integer(int_size) :: num, r
num = n
r = 0_int_size
do while( num >= 64 )
r = ior( r, iand(num, 1_int_size) )
num = ishft(num, -1_int_size)
end do
min_run = num + r
end function calc_min_run
pure subroutine insertion_sort( array )
! Sorts `ARRAY` using an insertion sort.
character(len=*), intent(inout) :: array(0:)
integer(int_size) :: i, j
character(len=len(array)) :: key
do j=1, size(array, kind=int_size)-1
key = array(j)
i = j - 1
do while( i >= 0 )
if ( array(i) ${signoppt}$= key ) exit
array(i+1) = array(i)
i = i - 1
end do
array(i+1) = key
end do
end subroutine insertion_sort
pure function collapse( runs ) result ( r )
! Examine the stack of runs waiting to be merged, identifying adjacent runs
! to be merged until the stack invariants are restablished:
!
! 1. len(-3) > len(-2) + len(-1)
! 2. len(-2) > len(-1)
integer(int_size) :: r
type(run_type), intent(in), target :: runs(0:)
integer(int_size) :: n
logical :: test
n = size(runs, kind=int_size)
test = .false.
if (n >= 2) then
if ( runs( n-1 ) % base == 0 .or. &
runs( n-2 ) % len <= runs(n-1) % len ) then
test = .true.
else if ( n >= 3 ) then ! X exists
if ( runs(n-3) % len <= &
runs(n-2) % len + runs(n-1) % len ) then
test = .true.
! |X| <= |Y| + |Z| => will need to merge due to rho1 or rho2
else if( n >= 4 ) then
if ( runs(n-4) % len <= &
runs(n-3) % len + runs(n-2) % len ) then
test = .true.
! |W| <= |X| + |Y| => will need to merge due to rho1 or rho3
end if
end if
end if
end if
if ( test ) then
! By default merge Y & Z, rho2 or rho3
if ( n >= 3 ) then
if ( runs(n-3) % len < runs(n-1) % len ) then
r = n - 3
! |X| < |Z| => merge X & Y, rho1
return
end if
end if
r = n - 2
! |Y| <= |Z| => merge Y & Z, rho4
return
else
r = -1
end if
end function collapse
pure subroutine insert_head( array )
! Inserts `array(0)` into the pre-sorted sequence `array(1:)` so that the
! whole `array(0:)` becomes sorted, copying the first element into
! a temporary variable, iterating until the right place for it is found.
! copying every traversed element into the slot preceding it, and finally,
! copying data from the temporary variable into the resulting hole.
character(len=*), intent(inout) :: array(0:)
character(len=len(array)) :: tmp
integer(int_size) :: i
tmp = array(0)
find_hole: do i=1, size(array, kind=int_size)-1
if ( array(i) ${signt}$= tmp ) exit find_hole
array(i-1) = array(i)
end do find_hole
array(i-1) = tmp
end subroutine insert_head
subroutine merge_sort( array, buf )
! The Rust merge sort borrows some (but not all) of the ideas from TimSort,
! which is described in detail at
! (http://svn.python.org/projects/python/trunk/Objects/listsort.txt).
!
! The algorithm identifies strictly descending and non-descending
! subsequences, which are called natural runs. Where these runs are less
! than a minimum run size they are padded by adding additional samples
! using an insertion sort. The merge process is driven by a stack of
! pending unmerged runs. Each newly found run is pushed onto the stack,
! and then pairs of adjacentd runs are merged until these two invariants
! are satisfied:
!
! 1. for every `i` in `1..size(runs)-1`: `runs(i - 1)%len > runs(i)%len`
! 2. for every `i` in `2..size(runs)-1`: `runs(i - 2)%len >
! runs(i - 1)%len + runs(i)%len`
!
! The invariants ensure that the total running time is `O(n log n)`
! worst-case.
character(len=*), intent(inout) :: array(0:)
character(len=len(array)), intent(inout) :: buf(0:)
integer(int_size) :: array_size, finish, min_run, r, r_count, &
start
type(run_type) :: runs(0:max_merge_stack-1), left, right
array_size = size(array, kind=int_size)
! Very short runs are extended using insertion sort to span at least
! min_run elements. Slices of up to this length are sorted using insertion
! sort.
min_run = calc_min_run( array_size )
if ( array_size <= min_run ) then
if ( array_size >= 2 ) call insertion_sort( array )
return
end if
! Following Rust sort, natural runs in `array` are identified by traversing
! it backwards. By traversing it backward, merges more often go in the
! opposite direction (forwards). According to developers of Rust sort,
! merging forwards is slightly faster than merging backwards. Therefore
! identifying runs by traversing backwards should improve performance.
r_count = 0
finish = array_size - 1
do while ( finish >= 0 )
! Find the next natural run, and reverse it if it's strictly descending.
start = finish
if ( start > 0 ) then
start = start - 1
if ( array(start+1) ${signoppt}$ array(start) ) then
Descending: do while ( start > 0 )
if ( array(start) ${signt}$= array(start-1) ) &
exit Descending
start = start - 1
end do Descending
call reverse_segment( array(start:finish) )
else
Ascending: do while( start > 0 )
if ( array(start) ${signoppt}$ array(start-1) ) exit Ascending
start = start - 1
end do Ascending
end if
end if
! If the run is too short insert some more elements using an insertion sort.
Insert: do while ( start > 0 )
if ( finish - start >= min_run - 1 ) exit Insert
start = start - 1
call insert_head( array(start:finish) )
end do Insert
if ( start == 0 .and. finish == array_size - 1 ) return
runs(r_count) = run_type( base = start, &
len = finish - start + 1 )
finish = start-1
r_count = r_count + 1
! Determine whether pairs of adjacent runs need to be merged to satisfy
! the invariants, and, if so, merge them.
Merge_loop: do
r = collapse( runs(0:r_count - 1) )
if ( r < 0 .or. r_count <= 1 ) exit Merge_loop
left = runs( r + 1 )
right = runs( r )
call merge( array( left % base: &
right % base + right % len - 1 ), &
left % len, buf )
runs(r) = run_type( base = left % base, &
len = left % len + right % len )
if ( r == r_count - 3 ) runs(r+1) = runs(r+2)
r_count = r_count - 1
end do Merge_loop
end do
if ( r_count /= 1 ) &
error stop "MERGE_SORT completed without RUN COUNT == 1."
end subroutine merge_sort
pure subroutine merge( array, mid, buf )
! Merges the two non-decreasing runs `ARRAY(0:MID-1)` and `ARRAY(MID:)`
! using `BUF` as temporary storage, and stores the merged runs into
! `ARRAY(0:)`. `MID` must be > 0, and < `SIZE(ARRAY)-1`. Buffer `BUF`
! must be long enough to hold the shorter of the two runs.
character(len=*), intent(inout) :: array(0:)
integer(int_size), intent(in) :: mid
character(len=len(array)), intent(inout) :: buf(0:)
integer(int_size) :: array_len, i, j, k
array_len = size(array, kind=int_size)
! Merge first copies the shorter run into `buf`. Then, depending on which
! run was shorter, it traces the copied run and the longer run forwards
! (or backwards), comparing their next unprocessed elements and then
! copying the lesser (or greater) one into `array`.
if ( mid <= array_len - mid ) then ! The left run is shorter.
buf(0:mid-1) = array(0:mid-1)
i = 0
j = mid
merge_lower: do k = 0, array_len-1
if ( buf(i) ${signoppt}$= array(j) ) then
array(k) = buf(i)
i = i + 1
if ( i >= mid ) exit merge_lower
else
array(k) = array(j)
j = j + 1
if ( j >= array_len ) then
array(k+1:) = buf(i:mid-1)
exit merge_lower
end if
end if
end do merge_lower
else ! The right run is shorter ! check that it is stable
buf(0:array_len-mid-1) = array(mid:array_len-1)
i = mid - 1
j = array_len - mid -1
merge_upper: do k = array_len-1, 0, -1
if ( buf(j) ${signt}$= array(i) ) then
array(k) = buf(j)
j = j - 1
if ( j < 0 ) exit merge_upper
else
array(k) = array(i)
i = i - 1
if ( i < 0 ) then
array(0:k-1) = buf(0:j)
exit merge_upper
end if
end if
end do merge_upper
end if
end subroutine merge
pure subroutine reverse_segment( array )
! Reverse a segment of an array in place
character(len=*), intent(inout) :: array(0:)
integer(int_size) :: lo, hi
character(len=len(array)) :: temp
lo = 0
hi = size( array, kind=int_size ) - 1
do while( lo < hi )
temp = array(lo)
array(lo) = array(hi)
array(hi) = temp
lo = lo + 1
hi = hi - 1
end do
end subroutine reverse_segment
end subroutine char_${sname}$_ord_sort
#:endfor
end submodule stdlib_sorting_ord_sort