diff --git a/rust/arrow/src/compute/kernels/sort.rs b/rust/arrow/src/compute/kernels/sort.rs index f5472738e7c..738178f15d4 100644 --- a/rust/arrow/src/compute/kernels/sort.rs +++ b/rust/arrow/src/compute/kernels/sort.rs @@ -35,14 +35,59 @@ use TimeUnit::*; /// /// Returns an `ArrowError::ComputeError(String)` if the array type is either unsupported by `sort_to_indices` or `take`. /// +/// # Example +/// ```rust +/// # use std::sync::Arc; +/// # use arrow::array::{Int32Array, ArrayRef}; +/// # use arrow::error::Result; +/// # use arrow::compute::kernels::sort::sort; +/// # fn main() -> Result<()> { +/// let array: ArrayRef = Arc::new(Int32Array::from(vec![5, 4, 3, 2, 1])); +/// let sorted_array = sort(&array, None).unwrap(); +/// let sorted_array = sorted_array.as_any().downcast_ref::().unwrap(); +/// assert_eq!(sorted_array, &Int32Array::from(vec![1, 2, 3, 4, 5])); +/// # Ok(()) +/// # } +/// ``` pub fn sort(values: &ArrayRef, options: Option) -> Result { let indices = sort_to_indices(values, options, None)?; take(values.as_ref(), &indices, None) } /// Sort the `ArrayRef` partially. -/// It's unstable_sort, may not preserve the order of equal elements -/// Return an sorted `ArrayRef`, discarding the data after limit. +/// +/// If `limit` is specified, the resulting array will contain only +/// first `limit` in the sort order. Any data data after the limit +/// will be discarded. +/// +/// Note: this is an unstable_sort, meaning it may not preserve the +/// order of equal elements. +/// +/// # Example +/// ```rust +/// # use std::sync::Arc; +/// # use arrow::array::{Int32Array, ArrayRef}; +/// # use arrow::error::Result; +/// # use arrow::compute::kernels::sort::{sort_limit, SortOptions}; +/// # fn main() -> Result<()> { +/// let array: ArrayRef = Arc::new(Int32Array::from(vec![5, 4, 3, 2, 1])); +/// +/// // Find the the top 2 items +/// let sorted_array = sort_limit(&array, None, Some(2)).unwrap(); +/// let sorted_array = sorted_array.as_any().downcast_ref::().unwrap(); +/// assert_eq!(sorted_array, &Int32Array::from(vec![1, 2])); +/// +/// // Find the bottom top 2 items +/// let options = Some(SortOptions { +/// descending: true, +/// ..Default::default() +/// }); +/// let sorted_array = sort_limit(&array, options, Some(2)).unwrap(); +/// let sorted_array = sorted_array.as_any().downcast_ref::().unwrap(); +/// assert_eq!(sorted_array, &Int32Array::from(vec![5, 4])); +/// # Ok(()) +/// # } +/// ``` pub fn sort_limit( values: &ArrayRef, options: Option,