Skip to content

Commit

Permalink
fix[rust]: fix and test sorted fast paths (#4457)
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 committed Aug 17, 2022
1 parent bf7b091 commit f161659
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
9 changes: 7 additions & 2 deletions polars/polars-core/src/chunked_array/ops/sort/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,10 @@ macro_rules! sort_with_fast_path {
return $ca.clone();
}

if $options.descending && $ca.is_sorted_reverse() || $ca.is_sorted() {
// we can clone if we sort in same order
if $options.descending && $ca.is_sorted_reverse() || ($ca.is_sorted() && !$options.descending) {
// there are nulls
if $ca.has_validity() {
if $ca.null_count() > 0 {
// if the nulls are already last we can clone
if $options.nulls_last && $ca.get($ca.len() - 1).is_none() ||
// if the nulls are already first we can clone
Expand All @@ -146,6 +147,10 @@ macro_rules! sort_with_fast_path {
return $ca.clone();
}
}
// we can reverse if we sort in other order
else if ($options.descending && $ca.is_sorted() || $ca.is_sorted_reverse()) && $ca.null_count() == 0 {
return $ca.reverse()
};


}}
Expand Down
14 changes: 14 additions & 0 deletions py-polars/tests/test_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,3 +195,17 @@ def test_sorted_flag_reverse() -> None:
s = pl.arange(0, 7, eager=True)
assert s.flags["SORTED_ASC"]
assert s.reverse().flags["SORTED_DESC"]


def test_sorted_fast_paths() -> None:
s = pl.Series([1, 2, 3]).sort()
rev = s.sort(reverse=True)

assert rev.to_list() == [3, 2, 1]
assert s.sort().to_list() == [1, 2, 3]

s = pl.Series([None, 1, 2, 3]).sort()
rev = s.sort(reverse=True)
assert rev.to_list() == [None, 3, 2, 1]
assert rev.sort(reverse=True).to_list() == [None, 3, 2, 1]
assert rev.sort().to_list() == [None, 1, 2, 3]

0 comments on commit f161659

Please sign in to comment.