Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions include/xtensor/misc/xsort.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ namespace xt
return comp(*(data_begin + i), *(data_begin + j));
}
);
break;
}
case (sorting_method::stable):
{
Expand All @@ -329,6 +330,7 @@ namespace xt
return comp(*(data_begin + i), *(data_begin + j));
}
);
break;
}
}
}
Expand Down
42 changes: 42 additions & 0 deletions test/test_xsort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#include <algorithm>
#include <numeric>
#include <vector>

#include "xtensor/containers/xadapt.hpp"
#include "xtensor/containers/xarray.hpp"
#include "xtensor/containers/xfixed.hpp"
Expand Down Expand Up @@ -176,6 +180,44 @@ namespace xt
EXPECT_EQ(ex, xt::argsort(a, {0}, xt::sorting_method::stable));
}

TEST(xsort, argsort_quick_sorts_once)
{
// The quick method must not fall through to the stable sort: both
// orderings are valid, so only the number of comparisons tells them apart.
const std::vector<double> data = {5., 3., 8., 1., 9., 2., 7., 4., 6., 0., 3., 8., 1., 5., 2.};

std::size_t argsort_comparisons = 0;
std::vector<std::size_t> indices(data.size());
detail::argsort_iter(
data.cbegin(),
data.cend(),
indices.begin(),
indices.end(),
[&argsort_comparisons](double lhs, double rhs)
{
++argsort_comparisons;
return lhs < rhs;
},
sorting_method::quick
);

std::size_t sort_comparisons = 0;
std::vector<std::size_t> expected(data.size());
std::iota(expected.begin(), expected.end(), std::size_t(0));
std::sort(
expected.begin(),
expected.end(),
[&](std::size_t i, std::size_t j)
{
++sort_comparisons;
return data[i] < data[j];
}
);

EXPECT_EQ(indices, expected);
EXPECT_EQ(argsort_comparisons, sort_comparisons);
}

TEST(xsort, sort_easy)
{
xarray<double> a = {{5, 3, 1}, {4, 4, 4}};
Expand Down
Loading