Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stop using rand(lo:hi) for QuickerSort pivot selection #48241

Merged
merged 2 commits into from
Jan 12, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 4 additions & 10 deletions base/sort.jl
Original file line number Diff line number Diff line change
Expand Up @@ -983,21 +983,15 @@ QuickerSort(lo::Union{Integer, Missing}, hi::Union{Integer, Missing}) = QuickerS
QuickerSort(lo::Union{Integer, Missing}, next::Algorithm=SMALL_ALGORITHM) = QuickerSort(lo, lo, next)
QuickerSort(r::OrdinalRange, next::Algorithm=SMALL_ALGORITHM) = QuickerSort(first(r), last(r), next)

# select a pivot for QuickerSort
#
# 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
# sets `pivot_dest[pivot_index+pivot_index_offset] = pivot` and returns that index.
function partition!(t::AbstractVector, lo::Integer, hi::Integer, offset::Integer, o::Ordering,
v::AbstractVector, rev::Bool, pivot_dest::AbstractVector, pivot_index_offset::Integer)
pivot_index = select_pivot(lo, hi)
# Ideally we would use `pivot_index = rand(lo:hi)`, but a dependency on Random.jl
# complicates things and some folks object to mutating the global RNG in sorting.
LilithHafner marked this conversation as resolved.
Show resolved Hide resolved
pivot_index = typeof(hi-lo)(hash(lo) % (hi-lo+1)) + lo
@inbounds begin
pivot = v[pivot_index]
while lo < pivot_index
Expand Down
6 changes: 0 additions & 6 deletions stdlib/Random/src/Random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -434,10 +434,4 @@ true
"""
seed!(rng::AbstractRNG, ::Nothing) = seed!(rng)

# Randomize quicksort pivot selection. This code is here because of bootstrapping:
# we need to sort things before we load this standard library.
# TODO move this into Sort.jl
Base.delete_method(only(methods(Base.Sort.select_pivot)))
Base.Sort.select_pivot(lo::Integer, hi::Integer) = rand(lo:hi)

end # module