# Any sorting function in Julia that is as fast as Matlab's maxk?

**URL:** <https://discourse.julialang.org/t/any-sorting-function-in-julia-that-is-as-fast-as-matlabs-maxk/14105>\
**Category:** Performance\
**Tags:** performance, matlab, sort, sortperm\
**Created:** [August 27, 2018, 2:24am UTC](https://discourse.julialang.org/t/any-sorting-function-in-julia-that-is-as-fast-as-matlabs-maxk/14105 "2018-08-27T02:24:35Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![xiaodai](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaodai/32/15937_2.png) [@xiaodai](https://discourse.julialang.org/u/xiaodai)\
**Post date:** [August 27, 2018, 6:27am UTC](https://discourse.julialang.org/t/any-sorting-function-in-julia-that-is-as-fast-as-matlabs-maxk/14105/2 "2018-08-27T06:27:14Z")

</div>

How large is your array? My [SortingLab.jl](https://github.com/xiaodaigh/SortingLab.jl) has a fast sortperm (`fsortperm`) for sorting integers but not floats. It’s not hard to adapt the algorithm for floats as follows. The issue with `fsortperm` is that it doesn’t know to stop once it has found the top `k` values but instead returns everything first so it may not be as efficient.

```julia
# uint_mapping stolen from SortingAlgorithms.jl
uint_mapping(x::Float64) = (y = reinterpret(Int64, x); reinterpret(UInt64, ifelse(y < 0, ~y, xor(y, typemin(Int64)))))

maxk(Q,k) = begin
    Qunit = uint_mapping.(Q)
    res = SortingLab.fsortperm(Qunit)
    Q[res[end-(k-1):end]]
end

Q = randn(10000)
@benchmark maxk($Q, 10)

```

those are the results from Juliabox (v0.6.2), so I think it’s pretty good for such a small size Q (length = 1000)

```julia
BenchmarkTools.Trial: 
  memory estimate: 133.78 KiB
  allocs estimate: 34
  --------------
  minimum time: 97.704 μs (0.00% GC)
  median time: 115.204 μs (0.00% GC)
  mean time: 139.580 μs (5.07% GC)
  maximum time: 100.319 ms (0.00% GC)
  --------------
  samples: 10000
  evals/sample: 1

```

Also the below is a better way to benchmark

```julia
using BenchmarkTools
@benchmark ind1=partialsortperm($Q, 1:10, rev=true);

```

would be a better way

---

_[View the full topic](https://discourse.julialang.org/t/any-sorting-function-in-julia-that-is-as-fast-as-matlabs-maxk/14105)._
