# Fastest way to partition array, given a condition

**URL:** <https://discourse.julialang.org/t/fastest-way-to-partition-array-given-a-condition/65243>\
**Category:** Performance\
**Tags:** sort\
**Created:** [July 24, 2021, 6:55pm UTC](https://discourse.julialang.org/t/fastest-way-to-partition-array-given-a-condition/65243 "2021-07-24T18:55:47Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [July 24, 2021, 7:59pm UTC](https://discourse.julialang.org/t/fastest-way-to-partition-array-given-a-condition/65243/8 "2021-07-24T19:59:24Z")

</div>

> [@lmiq](#):
>
> Anyone can think of a faster alternative?

This should minimize the number of swaps but the overall higher complexity doesn’t seem to pay off unless the swaps are more expensive than in the benchmark.

```julia
function partialsort_cutoff2!(x, cutoff)
    i, j = extrema(eachindex(x))
    while true
        while i < j && x[i] <= cutoff
            i += 1
        end
        while j > i && x[j] > cutoff
            j -= 1
        end
        if j <= i
            return i - 1
        end
        x[i], x[j] = x[j], x[i]
    end
end

```

Edit: There’s a corner case bug if all elements are lower than the cutoff.

---

_[View the full topic](https://discourse.julialang.org/t/fastest-way-to-partition-array-given-a-condition/65243)._
