select!(v, k, [by=,] [lt=,] [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 via a non-stable algorithm. 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 select! does not fully sort the input array.


  1. Select the k-th smallest element in an array:

    julia> arr = [10, 5, 8, 3, 2, 6];
    julia> select!(arr, 3)

    This example selects the 3rd smallest element from the array arr. The array arr will be partially sorted, and the value 6 is returned.

  2. Select a range of elements from an array:

    julia> arr = [7, 2, 9, 4, 1, 6];
    julia> select!(arr, 2:4)
    3-element Array{Int64,1}:

    It selects a range of elements from index 2 to 4 in the array arr. The array arr will be partially sorted, and an array of values [2, 4, 6] is returned.

  3. Sort array in descending order:
    julia> arr = [5, 2, 8, 1, 9, 3];
    julia> select!(arr, 1, rev=true)

    It partially sorts the array arr in descending order and selects the largest value. The value 9 is returned.

Common mistake example:

julia> arr = [3, 7, 1];
julia> select!(arr, 4)
ERROR: BoundsError: attempt to access 3-element Array{Int64,1} at index [4]

In this example, the index provided is out of bounds for the array. Ensure that the index or range passed to select! is within the valid range of the vector v.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field

Checking you are not a robot: