-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
sort.jl
1962 lines (1620 loc) · 62.3 KB
/
sort.jl
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: https://julialang.org/license
module Sort
using Base.Order
using Base: copymutable, midpoint, require_one_based_indexing,
sub_with_overflow, add_with_overflow, OneTo, BitSigned, BitIntegerType
import Base:
sort,
sort!,
issorted,
sortperm,
to_indices
export # also exported by Base
# order-only:
issorted,
searchsorted,
searchsortedfirst,
searchsortedlast,
insorted,
# order & algorithm:
sort,
sort!,
sortperm,
sortperm!,
partialsort,
partialsort!,
partialsortperm,
partialsortperm!,
# algorithms:
InsertionSort,
QuickSort,
MergeSort,
PartialQuickSort
export # not exported by Base
Algorithm,
DEFAULT_UNSTABLE,
DEFAULT_STABLE,
SMALL_ALGORITHM,
SMALL_THRESHOLD
## functions requiring only ordering ##
function issorted(itr, order::Ordering)
y = iterate(itr)
y === nothing && return true
prev, state = y
y = iterate(itr, state)
while y !== nothing
this, state = y
lt(order, this, prev) && return false
prev = this
y = iterate(itr, state)
end
return true
end
"""
issorted(v, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
Test whether a vector is in sorted order. The `lt`, `by` and `rev` keywords modify what
order is considered to be sorted just as they do for [`sort`](@ref).
# Examples
```jldoctest
julia> issorted([1, 2, 3])
true
julia> issorted([(1, "b"), (2, "a")], by = x -> x[1])
true
julia> issorted([(1, "b"), (2, "a")], by = x -> x[2])
false
julia> issorted([(1, "b"), (2, "a")], by = x -> x[2], rev=true)
true
```
"""
issorted(itr;
lt=isless, by=identity, rev::Union{Bool,Nothing}=nothing, order::Ordering=Forward) =
issorted(itr, ord(lt,by,rev,order))
function partialsort!(v::AbstractVector, k::Union{Integer,OrdinalRange}, o::Ordering)
_sort!(v, _PartialQuickSort(k), o, (;))
maybeview(v, k)
end
maybeview(v, k) = view(v, k)
maybeview(v, k::Integer) = v[k]
"""
partialsort!(v, k; by=<transform>, lt=<comparison>, rev=false)
Partially sort the vector `v` in place, according to the order specified by `by`, `lt` and
`rev` so that the value at index `k` (or range of adjacent values if `k` is a range) occurs
at the position where it would appear if the array were fully sorted. If `k` is a single
index, that value is returned; if `k` is a range, an array of values at those indices is
returned. Note that `partialsort!` may not fully sort the input array.
# Examples
```jldoctest
julia> a = [1, 2, 4, 3, 4]
5-element Vector{Int64}:
1
2
4
3
4
julia> partialsort!(a, 4)
4
julia> a
5-element Vector{Int64}:
1
2
3
4
4
julia> a = [1, 2, 4, 3, 4]
5-element Vector{Int64}:
1
2
4
3
4
julia> partialsort!(a, 4, rev=true)
2
julia> a
5-element Vector{Int64}:
4
4
3
2
1
```
"""
partialsort!(v::AbstractVector, k::Union{Integer,OrdinalRange};
lt=isless, by=identity, rev::Union{Bool,Nothing}=nothing, order::Ordering=Forward) =
partialsort!(v, k, ord(lt,by,rev,order))
"""
partialsort(v, k, by=<transform>, lt=<comparison>, rev=false)
Variant of [`partialsort!`](@ref) which copies `v` before partially sorting it, thereby returning the
same thing as `partialsort!` but leaving `v` unmodified.
"""
partialsort(v::AbstractVector, k::Union{Integer,OrdinalRange}; kws...) =
partialsort!(copymutable(v), k; kws...)
# reference on sorted binary search:
# http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary
# index of the first value of vector a that is greater than or equal to x;
# returns lastindex(v)+1 if x is greater than all values in v.
function searchsortedfirst(v::AbstractVector, x, lo::T, hi::T, o::Ordering)::keytype(v) where T<:Integer
hi = hi + T(1)
len = hi - lo
@inbounds while len != 0
half_len = len >>> 0x01
m = lo + half_len
if lt(o, v[m], x)
lo = m + 1
len -= half_len + 1
else
hi = m
len = half_len
end
end
return lo
end
# index of the last value of vector a that is less than or equal to x;
# returns firstindex(v)-1 if x is less than all values of v.
function searchsortedlast(v::AbstractVector, x, lo::T, hi::T, o::Ordering)::keytype(v) where T<:Integer
u = T(1)
lo = lo - u
hi = hi + u
@inbounds while lo < hi - u
m = midpoint(lo, hi)
if lt(o, x, v[m])
hi = m
else
lo = m
end
end
return lo
end
# returns the range of indices of v equal to x
# if v does not contain x, returns a 0-length range
# indicating the insertion point of x
function searchsorted(v::AbstractVector, x, ilo::T, ihi::T, o::Ordering)::UnitRange{keytype(v)} where T<:Integer
u = T(1)
lo = ilo - u
hi = ihi + u
@inbounds while lo < hi - u
m = midpoint(lo, hi)
if lt(o, v[m], x)
lo = m
elseif lt(o, x, v[m])
hi = m
else
a = searchsortedfirst(v, x, max(lo,ilo), m, o)
b = searchsortedlast(v, x, m, min(hi,ihi), o)
return a : b
end
end
return (lo + 1) : (hi - 1)
end
function searchsortedlast(a::AbstractRange{<:Real}, x::Real, o::DirectOrdering)::keytype(a)
require_one_based_indexing(a)
f, h, l = first(a), step(a), last(a)
if lt(o, x, f)
0
elseif h == 0 || !lt(o, x, l)
length(a)
else
n = round(Integer, (x - f) / h + 1)
lt(o, x, a[n]) ? n - 1 : n
end
end
function searchsortedfirst(a::AbstractRange{<:Real}, x::Real, o::DirectOrdering)::keytype(a)
require_one_based_indexing(a)
f, h, l = first(a), step(a), last(a)
if !lt(o, f, x)
1
elseif h == 0 || lt(o, l, x)
length(a) + 1
else
n = round(Integer, (x - f) / h + 1)
lt(o, a[n], x) ? n + 1 : n
end
end
function searchsortedlast(a::AbstractRange{<:Integer}, x::Real, o::DirectOrdering)::keytype(a)
require_one_based_indexing(a)
f, h, l = first(a), step(a), last(a)
if lt(o, x, f)
0
elseif h == 0 || !lt(o, x, l)
length(a)
else
if o isa ForwardOrdering
fld(floor(Integer, x) - f, h) + 1
else
fld(ceil(Integer, x) - f, h) + 1
end
end
end
function searchsortedfirst(a::AbstractRange{<:Integer}, x::Real, o::DirectOrdering)::keytype(a)
require_one_based_indexing(a)
f, h, l = first(a), step(a), last(a)
if !lt(o, f, x)
1
elseif h == 0 || lt(o, l, x)
length(a) + 1
else
if o isa ForwardOrdering
cld(ceil(Integer, x) - f, h) + 1
else
cld(floor(Integer, x) - f, h) + 1
end
end
end
searchsorted(a::AbstractRange{<:Real}, x::Real, o::DirectOrdering) =
searchsortedfirst(a, x, o) : searchsortedlast(a, x, o)
for s in [:searchsortedfirst, :searchsortedlast, :searchsorted]
@eval begin
$s(v::AbstractVector, x, o::Ordering) = $s(v,x,firstindex(v),lastindex(v),o)
$s(v::AbstractVector, x;
lt=isless, by=identity, rev::Union{Bool,Nothing}=nothing, order::Ordering=Forward) =
$s(v,x,ord(lt,by,rev,order))
end
end
"""
searchsorted(a, x; by=<transform>, lt=<comparison>, rev=false)
Return the range of indices of `a` which compare as equal to `x` (using binary search)
according to the order specified by the `by`, `lt` and `rev` keywords, assuming that `a`
is already sorted in that order. Return an empty range located at the insertion point
if `a` does not contain values equal to `x`.
See also: [`insorted`](@ref), [`searchsortedfirst`](@ref), [`sort`](@ref), [`findall`](@ref).
# Examples
```jldoctest
julia> searchsorted([1, 2, 4, 5, 5, 7], 4) # single match
3:3
julia> searchsorted([1, 2, 4, 5, 5, 7], 5) # multiple matches
4:5
julia> searchsorted([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle
3:2
julia> searchsorted([1, 2, 4, 5, 5, 7], 9) # no match, insert at end
7:6
julia> searchsorted([1, 2, 4, 5, 5, 7], 0) # no match, insert at start
1:0
```
""" searchsorted
"""
searchsortedfirst(a, x; by=<transform>, lt=<comparison>, rev=false)
Return the index of the first value in `a` greater than or equal to `x`, according to the
specified order. Return `lastindex(a) + 1` if `x` is greater than all values in `a`.
`a` is assumed to be sorted.
`insert!`ing `x` at this index will maintain sorted order.
See also: [`searchsortedlast`](@ref), [`searchsorted`](@ref), [`findfirst`](@ref).
# Examples
```jldoctest
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 4) # single match
3
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 5) # multiple matches
4
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle
3
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 9) # no match, insert at end
7
julia> searchsortedfirst([1, 2, 4, 5, 5, 7], 0) # no match, insert at start
1
```
""" searchsortedfirst
"""
searchsortedlast(a, x; by=<transform>, lt=<comparison>, rev=false)
Return the index of the last value in `a` less than or equal to `x`, according to the
specified order. Return `firstindex(a) - 1` if `x` is less than all values in `a`. `a` is
assumed to be sorted.
# Examples
```jldoctest
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 4) # single match
3
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 5) # multiple matches
5
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle
2
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 9) # no match, insert at end
6
julia> searchsortedlast([1, 2, 4, 5, 5, 7], 0) # no match, insert at start
0
```
""" searchsortedlast
"""
insorted(x, a; by=<transform>, lt=<comparison>, rev=false) -> Bool
Determine whether an item `x` is in the sorted collection `a`, in the sense that
it is [`==`](@ref) to one of the values of the collection according to the order
specified by the `by`, `lt` and `rev` keywords, assuming that `a` is already
sorted in that order, see [`sort`](@ref) for the keywords.
See also [`in`](@ref).
# Examples
```jldoctest
julia> insorted(4, [1, 2, 4, 5, 5, 7]) # single match
true
julia> insorted(5, [1, 2, 4, 5, 5, 7]) # multiple matches
true
julia> insorted(3, [1, 2, 4, 5, 5, 7]) # no match
false
julia> insorted(9, [1, 2, 4, 5, 5, 7]) # no match
false
julia> insorted(0, [1, 2, 4, 5, 5, 7]) # no match
false
```
!!! compat "Julia 1.6"
`insorted` was added in Julia 1.6.
"""
function insorted end
insorted(x, v::AbstractVector; kw...) = !isempty(searchsorted(v, x; kw...))
insorted(x, r::AbstractRange) = in(x, r)
## Alternative keyword management
macro getkw(syms...)
getters = (getproperty(Sort, Symbol(:_, sym)) for sym in syms)
Expr(:block, (:($(esc(:((kw, $sym) = $getter(v, o, kw))))) for (sym, getter) in zip(syms, getters))...)
end
for (sym, deps, exp, type) in [
(:lo, (), :(firstindex(v)), Integer),
(:hi, (), :(lastindex(v)), Integer),
(:mn, (), :(throw(ArgumentError("mn is needed but has not been computed"))), :(eltype(v))),
(:mx, (), :(throw(ArgumentError("mx is needed but has not been computed"))), :(eltype(v))),
(:range, (:mn, :mx), quote
o isa DirectOrdering || throw(ArgumentError("Cannot compute range under ordering $o"))
maybe_unsigned(o === Reverse ? mn-mx : mx-mn)
end, Integer),
(:umn, (:mn,), :(uint_map(mn, o)), Unsigned),
(:umx, (:mx,), :(uint_map(mx, o)), Unsigned),
(:urange, (:umn, :umx), :(umx-umn), Unsigned),
(:bits, (:urange,), :(unsigned(8sizeof(urange) - leading_zeros(urange))), Unsigned),
(:scratch, (), nothing, :(Union{Nothing, Vector})), # could have different eltype
(:allow_legacy_dispatch, (), true, Bool)]
str = string(sym)
usym = Symbol(:_, sym)
@eval function $usym(v, o, kw)
Symbol($str) ∈ keys(kw) && return kw, kw[Symbol($str)]::$type # TODO this interpolation feels too complicated
@getkw $(deps...)
$sym = $exp
(;kw..., $sym), $sym::$type
end
end
## Scratch space management
"""
make_scratch(scratch::Union{Nothing, Vector}, T::Type, len::Integer)
Returns `(s, t)` where `t` is an `AbstractVector` of type `T` with length at least `len`
that is backed by the `Vector` `s`. If `scratch !== nothing`, then `s === scratch`.
This function will allocate a new vector if `scratch === nothing`, `resize!` `scratch` if it
is too short, and `reinterpret` `scratch` if its eltype is not `T`.
"""
function make_scratch(scratch::Nothing, T::Type, len::Integer)
s = Vector{T}(undef, len)
s, s
end
function make_scratch(scratch::Vector{T}, ::Type{T}, len::Integer) where T
len > length(scratch) && resize!(scratch, len)
scratch, scratch
end
function make_scratch(scratch::Vector, T::Type, len::Integer)
len_bytes = len * sizeof(T)
len_scratch = div(len_bytes, sizeof(eltype(scratch)))
len_scratch > length(scratch) && resize!(scratch, len_scratch)
scratch, reinterpret(T, scratch)
end
## sorting algorithm components ##
"""
_sort!(v::AbstractVector, a::Algorithm, o::Ordering, kw; t, offset)
An internal function that sorts `v` using the algorithm `a` under the ordering `o`,
subject to specifications provided in `kw` (such as `lo` and `hi` in which case it only
sorts `view(v, lo:hi)`)
Returns a scratch space if provided or constructed during the sort, or `nothing` if
no scratch space is present.
!!! note
`_sort!` modifies but does not return `v`.
A returned scratch space will be a `Vector{T}` where `T` is usually the eltype of `v`. There
are some exceptions, for example if `eltype(v) == Union{Missing, T}` then the scratch space
may be be a `Vector{T}` due to `MissingOptimization` changing the eltype of `v` to `T`.
`t` is an appropriate scratch space for the algorithm at hand, to be accessed as
`t[i + offset]`. `t` is used for an algorithm to pass a scratch space back to itself in
internal or recursive calls.
"""
function _sort! end
abstract type Algorithm end
"""
MissingOptimization(next) <: Algorithm
Filter out missing values.
Missing values are placed after other values according to `DirectOrdering`s. This pass puts
them there and passes on a view into the original vector that excludes the missing values.
This pass is triggered for both `sort([1, missing, 3])` and `sortperm([1, missing, 3])`.
"""
struct MissingOptimization{T <: Algorithm} <: Algorithm
next::T
end
struct WithoutMissingVector{T, U <: AbstractVector{Union{T, Missing}}} <: AbstractVector{T}
data::U
function WithoutMissingVector(data; unsafe=false)
if !unsafe && any(ismissing, data)
throw(ArgumentError("data must not contain missing values"))
end
new{nonmissingtype(eltype(data)), typeof(data)}(data)
end
end
Base.@propagate_inbounds function Base.getindex(v::WithoutMissingVector, i)
out = v.data[i]
@assert !(out isa Missing)
out::eltype(v)
end
Base.@propagate_inbounds function Base.setindex!(v::WithoutMissingVector{T}, x::T, i) where T
v.data[i] = x
v
end
Base.size(v::WithoutMissingVector) = size(v.data)
"""
send_to_end!(f::Function, v::AbstractVector; [lo, hi])
Send every element of `v` for which `f` returns `true` to the end of the vector and return
the index of the last element which for which `f` returns `false`.
`send_to_end!(f, v, lo, hi)` is equivalent to `send_to_end!(f, view(v, lo:hi))+lo-1`
Preserves the order of the elements that are not sent to the end.
"""
function send_to_end!(f::F, v::AbstractVector; lo=firstindex(v), hi=lastindex(v)) where F <: Function
i = lo
@inbounds while i <= hi && !f(v[i])
i += 1
end
j = i + 1
@inbounds while j <= hi
if !f(v[j])
v[i], v[j] = v[j], v[i]
i += 1
end
j += 1
end
i - 1
end
"""
send_to_end!(f::Function, v::AbstractVector, o::DirectOrdering[, end_stable]; lo, hi)
Return `(a, b)` where `v[a:b]` are the elements that are not sent to the end.
If `o isa ReverseOrdering` then the "end" of `v` is `v[lo]`.
If `end_stable` is set, the elements that are sent to the end are stable instead of the
elements that are not
"""
@inline send_to_end!(f::F, v::AbstractVector, ::ForwardOrdering, end_stable=false; lo, hi) where F <: Function =
end_stable ? (lo, hi-send_to_end!(!f, view(v, hi:-1:lo))) : (lo, send_to_end!(f, v; lo, hi))
@inline send_to_end!(f::F, v::AbstractVector, ::ReverseOrdering, end_stable=false; lo, hi) where F <: Function =
end_stable ? (send_to_end!(!f, v; lo, hi)+1, hi) : (hi-send_to_end!(f, view(v, hi:-1:lo))+1, hi)
function _sort!(v::AbstractVector, a::MissingOptimization, o::Ordering, kw)
@getkw lo hi
if nonmissingtype(eltype(v)) != eltype(v) && o isa DirectOrdering
lo, hi = send_to_end!(ismissing, v, o; lo, hi)
_sort!(WithoutMissingVector(v, unsafe=true), a.next, o, (;kw..., lo, hi))
elseif eltype(v) <: Integer && (o isa Perm{DirectOrdering} || o isa PermUnstable{DirectOrdering}) &&
nonmissingtype(eltype(o.data)) != eltype(o.data)
PermT = o isa Perm{DirectOrdering} ? Perm : PermUnstable
lo, hi = send_to_end!(i -> ismissing(@inbounds o.data[i]), v, o)
_sort!(v, a.next, PermT(o.order, WithoutMissingVector(o.data, unsafe=true)), (;kw..., lo, hi))
else
_sort!(v, a.next, o, kw)
end
end
"""
IEEEFloatOptimization(next) <: Algorithm
Move NaN values to the end, partition by sign, and reinterpret the rest as unsigned integers.
IEEE floating point numbers (`Float64`, `Float32`, and `Float16`) compare the same as
unsigned integers with the bits with a few exceptions. This pass
This pass is triggered for both `sort([1.0, NaN, 3.0])` and `sortperm([1.0, NaN, 3.0])`.
"""
struct IEEEFloatOptimization{T <: Algorithm} <: Algorithm
next::T
end
UIntType(::Type{Float16}) = UInt16
UIntType(::Type{Float32}) = UInt32
UIntType(::Type{Float64}) = UInt64
after_zero(::ForwardOrdering, x) = 0 <= x
after_zero(::ReverseOrdering, x) = x < 0
is_concrete_IEEEFloat(T::Type) = T <: Base.IEEEFloat && isconcretetype(T)
function _sort!(v::AbstractVector, a::IEEEFloatOptimization, o::Ordering, kw)
@getkw lo hi
if is_concrete_IEEEFloat(eltype(v)) && o isa DirectOrdering
lo, hi = send_to_end!(isnan, v, o, true; lo, hi)
iv = reinterpret(UIntType(eltype(v)), v)
j = send_to_end!(x -> after_zero(o, x), v; lo, hi)
scratch = _sort!(iv, a.next, Reverse, (;kw..., lo, hi=j))
if scratch === nothing # Union split
_sort!(iv, a.next, Forward, (;kw..., lo=j+1, hi, scratch))
else
_sort!(iv, a.next, Forward, (;kw..., lo=j+1, hi, scratch))
end
elseif eltype(v) <: Integer && (o isa Perm || o isa PermUnstable) &&
o.order isa DirectOrdering && is_concrete_IEEEFloat(eltype(o.data))
lo, hi = send_to_end!(i -> isnan(@inbounds o.data[i]), v, o.order, true; lo, hi)
ip = reinterpret(UIntType(eltype(o.data)), o.data)
j = send_to_end!(i -> after_zero(o.order, @inbounds o.data[i]), v; lo, hi)
PermT = o isa Perm ? Perm : PermUnstable
scratch = _sort!(v, a.next, PermT(Reverse, ip), (;kw..., lo, hi=j))
if scratch === nothing # Union split
_sort!(v, a.next, PermT(Forward, ip), (;kw..., lo=j+1, hi, scratch))
else
_sort!(v, a.next, PermT(Forward, ip), (;kw..., lo=j+1, hi, scratch))
end
else
_sort!(v, a.next, o, kw)
end
end
"""
BoolOptimization(next) <: Algorithm
Sort `AbstractVector{Bool}`s using a specialized version of counting sort.
Accesses each element at most twice (one read and one write), and performs at most two
comparisons.
"""
struct BoolOptimization{T <: Algorithm} <: Algorithm
next::T
end
_sort!(v::AbstractVector, a::BoolOptimization, o::Ordering, kw) = _sort!(v, a.next, o, kw)
function _sort!(v::AbstractVector{Bool}, ::BoolOptimization, o::Ordering, kw)
first = lt(o, false, true) ? false : lt(o, true, false) ? true : return v
@getkw lo hi scratch
count = 0
@inbounds for i in lo:hi
if v[i] == first
count += 1
end
end
@inbounds v[lo:lo+count-1] .= first
@inbounds v[lo+count:hi] .= !first
scratch
end
"""
IsUIntMappable(yes, no) <: Algorithm
Determines if the elements of a vector can be mapped to unsigned integers while preserving
their order under the specified ordering.
If they can be, dispatch to the `yes` algorithm and record the unsigned integer type that
the elements may be mapped to. Otherwise dispatch to the `no` algorithm.
"""
struct IsUIntMappable{T <: Algorithm, U <: Algorithm} <: Algorithm
yes::T
no::U
end
function _sort!(v::AbstractVector, a::IsUIntMappable, o::Ordering, kw)
if UIntMappable(eltype(v), o) !== nothing
_sort!(v, a.yes, o, kw)
else
_sort!(v, a.no, o, kw)
end
end
"""
Small{N}(small=SMALL_ALGORITHM, big) <: Algorithm
Sort inputs with `length(lo:hi) <= N` using the `small` algorithm. Otherwise use the `big`
algorithm.
"""
struct Small{N, T <: Algorithm, U <: Algorithm} <: Algorithm
small::T
big::U
end
Small{N}(small, big) where N = Small{N, typeof(small), typeof(big)}(small, big)
Small{N}(big) where N = Small{N}(SMALL_ALGORITHM, big)
function _sort!(v::AbstractVector, a::Small{N}, o::Ordering, kw) where N
@getkw lo hi
if (hi-lo) < N
_sort!(v, a.small, o, kw)
else
_sort!(v, a.big, o, kw)
end
end
"""
InsertionSort()
Use the insertion sort algorithm.
Insertion sort traverses the collection one element at a time, inserting
each element into its correct, sorted position in the output vector.
Characteristics:
* *stable*: preserves the ordering of elements which compare equal
(e.g. "a" and "A" in a sort of letters which ignores case).
* *in-place* in memory.
* *quadratic performance* in the number of elements to be sorted:
it is well-suited to small collections but should not be used for large ones.
"""
struct InsertionSort <: Algorithm end
const SMALL_ALGORITHM = InsertionSort()
function _sort!(v::AbstractVector, ::InsertionSort, o::Ordering, kw)
@getkw lo hi scratch
lo_plus_1 = (lo + 1)::Integer
@inbounds for i = lo_plus_1:hi
j = i
x = v[i]
while j > lo
y = v[j-1]
if !(lt(o, x, y)::Bool)
break
end
v[j] = y
j -= 1
end
v[j] = x
end
scratch
end
"""
CheckSorted(next) <: Algorithm
Check if the input is already sorted and for large inputs, also check if it is
reverse-sorted. The reverse-sorted check is unstable.
"""
struct CheckSorted{T <: Algorithm} <: Algorithm
next::T
end
function _sort!(v::AbstractVector, a::CheckSorted, o::Ordering, kw)
@getkw lo hi scratch
# For most arrays, a presorted check is cheap (overhead < 5%) and for most large
# arrays it is essentially free (<1%).
_issorted(v, lo, hi, o) && return scratch
# For most large arrays, a reverse-sorted check is essentially free (overhead < 1%)
if hi-lo >= 500 && _issorted(v, lo, hi, ReverseOrdering(o))
# If reversing is valid, do so. This does violates stability.
reverse!(v, lo, hi)
return scratch
end
_sort!(v, a.next, o, kw)
end
"""
ComputeExtrema(next) <: Algorithm
Compute the extrema of the input under the provided order.
If the minimum is no less than the maximum, then the input is already sorted. Otherwise,
dispatch to the `next` algorithm.
"""
struct ComputeExtrema{T <: Algorithm} <: Algorithm
next::T
end
function _sort!(v::AbstractVector, a::ComputeExtrema, o::Ordering, kw)
@getkw lo hi scratch
mn = mx = v[lo]
@inbounds for i in (lo+1):hi
vi = v[i]
lt(o, vi, mn) && (mn = vi)
lt(o, mx, vi) && (mx = vi)
end
mn, mx
lt(o, mn, mx) || return scratch # all same
_sort!(v, a.next, o, (;kw..., mn, mx))
end
"""
ConsiderCountingSort(counting=CountingSort(), next) <: Algorithm
If the input's range is small enough, use the `counting` algorithm. Otherwise, dispatch to
the `next` algorithm.
For most types, the threshold is if the range is shorter than half the length, but for types
larger than Int64, bitshifts are expensive and RadixSort is not viable, so the threshold is
much more generous.
"""
struct ConsiderCountingSort{T <: Algorithm, U <: Algorithm} <: Algorithm
counting::T
next::U
end
ConsiderCountingSort(next) = ConsiderCountingSort(CountingSort(), next)
function _sort!(v::AbstractVector{<:Integer}, a::ConsiderCountingSort, o::DirectOrdering, kw)
@getkw lo hi range
if range < (sizeof(eltype(v)) > 8 ? 5(hi-lo)-100 : div(hi-lo, 2))
_sort!(v, a.counting, o, kw)
else
_sort!(v, a.next, o, kw)
end
end
_sort!(v::AbstractVector, a::ConsiderCountingSort, o::Ordering, kw) = _sort!(v, a.next, o, kw)
"""
CountingSort <: Algorithm
Use the counting sort algorithm.
`CountingSort` is an algorithm for sorting integers that runs in Θ(length + range) time and
space. It counts the number of occurrences of each value in the input and then iterates
through those counts repopulating the input with the values in sorted order.
"""
struct CountingSort <: Algorithm end
maybe_reverse(o::ForwardOrdering, x) = x
maybe_reverse(o::ReverseOrdering, x) = reverse(x)
function _sort!(v::AbstractVector{<:Integer}, ::CountingSort, o::DirectOrdering, kw)
@getkw lo hi mn mx range scratch
offs = 1 - (o === Reverse ? mx : mn)
counts = fill(0, range+1) # TODO use scratch (but be aware of type stability)
@inbounds for i = lo:hi
counts[v[i] + offs] += 1
end
idx = lo
@inbounds for i = maybe_reverse(o, 1:range+1)
lastidx = idx + counts[i] - 1
val = i-offs
for j = idx:lastidx
v[j] = val
end
idx = lastidx + 1
end
scratch
end
"""
ConsiderRadixSort(radix=RadixSort(), next) <: Algorithm
If the number of bits in the input's range is small enough and the input supports efficient
bitshifts, use the `radix` algorithm. Otherwise, dispatch to the `next` algorithm.
"""
struct ConsiderRadixSort{T <: Algorithm, U <: Algorithm} <: Algorithm
radix::T
next::U
end
ConsiderRadixSort(next) = ConsiderRadixSort(RadixSort(), next)
function _sort!(v::AbstractVector, a::ConsiderRadixSort, o::DirectOrdering, kw)
@getkw bits lo hi
if sizeof(eltype(v)) <= 8 && bits+70 < 22log(hi-lo)
_sort!(v, a.radix, o, kw)
else
_sort!(v, a.next, o, kw)
end
end
"""
RadixSort <: Algorithm
Use the radix sort algorithm.
`RadixSort` is a stable least significant bit first radix sort algorithm that runs in
`O(length * log(range))` time and linear space.
It first sorts the entire vector by the last `chunk_size` bits, then by the second
to last `chunk_size` bits, and so on. Stability means that it will not reorder two elements
that compare equal. This is essential so that the order introduced by earlier,
less significant passes is preserved by later passes.
Each pass divides the input into `2^chunk_size == mask+1` buckets. To do this, it
* counts the number of entries that fall into each bucket
* uses those counts to compute the indices to move elements of those buckets into
* moves elements into the computed indices in the swap array
* switches the swap and working array
`chunk_size` is larger for larger inputs and determined by an empirical heuristic.
"""
struct RadixSort <: Algorithm end
function _sort!(v::AbstractVector, a::RadixSort, o::DirectOrdering, kw)
@getkw lo hi umn scratch bits
# At this point, we are committed to radix sort.
u = uint_map!(v, lo, hi, o)
# we subtract umn to avoid radixing over unnecessary bits. For example,
# Int32[3, -1, 2] uint_maps to UInt32[0x80000003, 0x7fffffff, 0x80000002]
# which uses all 32 bits, but once we subtract umn = 0x7fffffff, we are left with
# UInt32[0x00000004, 0x00000000, 0x00000003] which uses only 3 bits, and
# Float32[2.012, 400.0, 12.345] uint_maps to UInt32[0x3fff3b63, 0x3c37ffff, 0x414570a4]
# which is reduced to UInt32[0x03c73b64, 0x00000000, 0x050d70a5] using only 26 bits.
# the overhead for this subtraction is small enough that it is worthwhile in many cases.
# this is faster than u[lo:hi] .-= umn as of v1.9.0-DEV.100
@inbounds for i in lo:hi
u[i] -= umn
end
len = hi-lo + 1
U = UIntMappable(eltype(v), o)
scratch, t = make_scratch(scratch, eltype(v), len)
tu = reinterpret(U, t)
if radix_sort!(u, lo, hi, bits, tu, 1-lo)
uint_unmap!(v, u, lo, hi, o, umn)
else
uint_unmap!(v, tu, lo, hi, o, umn, 1-lo)
end
scratch
end
"""
PartialQuickSort(lo::Union{Integer, Missing}, hi::Union{Integer, Missing}, next::Algorithm) <: Algorithm
Indicate that a sorting function should use the partial quick sort algorithm.
Partial quick sort finds and sorts the elements that would end up in positions `lo:hi` using
[`QuickSort`](@ref). It is recursive and uses the `next` algorithm for small chunks
Characteristics:
* *stable*: preserves the ordering of elements which compare equal
(e.g. "a" and "A" in a sort of letters which ignores case).
* *not in-place* in memory.
* *divide-and-conquer*: sort strategy similar to [`MergeSort`](@ref).
"""
struct PartialQuickSort{L<:Union{Integer,Missing}, H<:Union{Integer,Missing}, T<:Algorithm} <: Algorithm
lo::L
hi::H
next::T
end
PartialQuickSort(k::Integer) = InitialOptimizations(PartialQuickSort(missing, k, SMALL_ALGORITHM))
PartialQuickSort(k::OrdinalRange) = InitialOptimizations(PartialQuickSort(first(k), last(k), SMALL_ALGORITHM))
_PartialQuickSort(k::Integer) = InitialOptimizations(PartialQuickSort(k:k))
_PartialQuickSort(k::OrdinalRange) = InitialOptimizations(PartialQuickSort(k))
"""
QuickSort
Indicate that a sorting function should use the quick sort algorithm.
Quick sort picks a pivot element, partitions the array based on the pivot,
and then sorts the elements before and after the pivot recursively.
Characteristics:
* *stable*: preserves the ordering of elements which compare equal
(e.g. "a" and "A" in a sort of letters which ignores case).
* *not in-place* in memory.
* *divide-and-conquer*: sort strategy similar to [`MergeSort`](@ref).
* *good performance* for almost all large collections.
* *quadratic worst case runtime* in pathological cases
(vanishingly rare for non-malicious input)
"""
const QuickSort = PartialQuickSort(missing, missing, SMALL_ALGORITHM)
# select a pivot for QuickSort
#
# This method is redefined to rand(lo:hi) in Random.jl
# We can't use rand here because it is not available in Core.Compiler and
# because rand is defined in the stdlib Random.jl after sorting is used in Base.
select_pivot(lo::Integer, hi::Integer) = typeof(hi-lo)(hash(lo) % (hi-lo+1)) + lo
# select a pivot, partition v[lo:hi] according
# to the pivot, and store the result in t[lo:hi].
#
# returns (pivot, pivot_index) where pivot_index is the location the pivot
# should end up, but does not set t[pivot_index] = pivot
function partition!(t::AbstractVector, lo::Integer, hi::Integer, offset::Integer, o::Ordering, v::AbstractVector, rev::Bool)
pivot_index = select_pivot(lo, hi)
@inbounds begin
pivot = v[pivot_index]
while lo < pivot_index
x = v[lo]
fx = rev ? !lt(o, x, pivot) : lt(o, pivot, x)
t[(fx ? hi : lo) - offset] = x
offset += fx
lo += 1