aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Functions/array/arraySort.cpp
blob: a853289e8ccdbfb46c6062f0e5c521aa32328d12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <Functions/array/arraySort.h>
#include <Functions/FunctionFactory.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
}

namespace
{

template <bool positive>
struct Less
{
    const IColumn & column;

    explicit Less(const IColumn & column_) : column(column_) { }

    bool operator()(size_t lhs, size_t rhs) const
    {
        if constexpr (positive)
            return column.compareAt(lhs, rhs, column, 1) < 0;
        else
            return column.compareAt(lhs, rhs, column, -1) > 0;
    }
};

}

template <bool positive, bool is_partial>
ColumnPtr ArraySortImpl<positive, is_partial>::execute(
    const ColumnArray & array,
    ColumnPtr mapped,
    const ColumnWithTypeAndName * fixed_arguments)
{
    [[maybe_unused]] const auto limit = [&]() -> size_t
    {
        if constexpr (is_partial)
        {
            if (!fixed_arguments)
                throw Exception(
                    ErrorCodes::LOGICAL_ERROR,
                    "Expected fixed arguments to get the limit for partial array sort"
                );
            return fixed_arguments[0].column.get()->getUInt(0);
        }
        return 0;
    }();

    const ColumnArray::Offsets & offsets = array.getOffsets();

    size_t size = offsets.size();
    size_t nested_size = array.getData().size();
    IColumn::Permutation permutation(nested_size);

    for (size_t i = 0; i < nested_size; ++i)
        permutation[i] = i;

    ColumnArray::Offset current_offset = 0;
    for (size_t i = 0; i < size; ++i)
    {
        auto next_offset = offsets[i];
        if constexpr (is_partial)
        {
            if (limit)
            {
                const auto effective_limit = std::min<size_t>(limit, next_offset - current_offset);
                ::partial_sort(&permutation[current_offset], &permutation[current_offset + effective_limit], &permutation[next_offset], Less<positive>(*mapped));
            }
            else
                ::sort(&permutation[current_offset], &permutation[next_offset], Less<positive>(*mapped));
        }
        else
            ::sort(&permutation[current_offset], &permutation[next_offset], Less<positive>(*mapped));
        current_offset = next_offset;
    }

    return ColumnArray::create(array.getData().permute(permutation, 0), array.getOffsetsPtr());
}

REGISTER_FUNCTION(ArraySort)
{
    factory.registerFunction<FunctionArraySort>();
    factory.registerFunction<FunctionArrayReverseSort>();

    factory.registerFunction<FunctionArrayPartialSort>(FunctionDocumentation{
        .description=R"(
Returns an array of the same size as the original array where elements in range `[1..limit]`
are sorted in ascending order. Remaining elements `(limit..N]` shall contain elements in unspecified order.
[example:simple_int]
[example:simple_string]

To retain only the sorted elements use `arrayResize`:
[example:retain_sorted]

If the `func` function is specified, sorting order is determined by the result of the `func`
function applied to the elements of the array.
[example:lambda_simple]

If `func` accepts multiple arguments, the `arrayPartialSort` function is passed several arrays
that the arguments of `func` will correspond to.
[example:lambda_complex]

For more details see documentation of `arraySort`.
)",
        .examples{
            {"simple_int", "SELECT arrayPartialSort(2, [5, 9, 1, 3])", ""},
            {"simple_string", "SELECT arrayPartialSort(2, ['expenses','lasso','embolism','gladly'])", ""},
            {"retain_sorted", "SELECT arrayResize(arrayPartialSort(2, [5, 9, 1, 3]), 2)", ""},
            {"lambda_simple", "SELECT arrayPartialSort((x) -> -x, 2, [5, 9, 1, 3])", ""},
            {"lambda_complex", "SELECT arrayPartialSort((x, y) -> -y, 1, [0, 1, 2], [1, 2, 3]) as res", ""}},
        .categories{"Array"}});

    factory.registerFunction<FunctionArrayPartialReverseSort>(FunctionDocumentation{
        .description=R"(
Returns an array of the same size as the original array where elements in range `[1..limit]`
are sorted in descending order. Remaining elements `(limit..N]` shall contain elements in unspecified order.
[example:simple_int]
[example:simple_string]

To retain only the sorted elements use `arrayResize`:
[example:retain_sorted]

If the `func` function is specified, sorting order is determined by the result of the `func`
function applied to the elements of the array.
[example:lambda_simple]

If `func` accepts multiple arguments, the `arrayPartialSort` function is passed several arrays
that the arguments of `func` will correspond to.
[example:lambda_complex]

For more details see documentation of `arraySort`.
)",
        .examples{
            {"simple_int", "SELECT arrayPartialReverseSort(2, [5, 9, 1, 3])", ""},
            {"simple_string", "SELECT arrayPartialReverseSort(2, ['expenses','lasso','embolism','gladly'])", ""},
            {"retain_sorted", "SELECT arrayResize(arrayPartialReverseSort(2, [5, 9, 1, 3]), 2)", ""},
            {"lambda_simple", "SELECT arrayPartialReverseSort((x) -> -x, 2, [5, 9, 1, 3])", ""},
            {"lambda_complex", "SELECT arrayPartialReverseSort((x, y) -> -y, 1, [0, 1, 2], [1, 2, 3]) as res", ""}},
        .categories{"Array"}});
}

}