Skip to content

Commit b5b774b

Browse files
headlessNodekgryte
andauthored
feat: add blas/ext/sort
PR-URL: #11512 Closes: stdlib-js/metr-issue-tracker#120 Co-authored-by: Athan Reines <kgryte@gmail.com> Reviewed-by: Athan Reines <kgryte@gmail.com>
1 parent ddd9fe3 commit b5b774b

11 files changed

Lines changed: 2663 additions & 0 deletions

File tree

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2026 The Stdlib Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
19+
-->
20+
21+
# sort
22+
23+
> Sort an input [ndarray][@stdlib/ndarray/ctor] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions.
24+
25+
<section class="usage">
26+
27+
## Usage
28+
29+
```javascript
30+
var sort = require( '@stdlib/blas/ext/sort' );
31+
```
32+
33+
#### sort( x\[, sortOrder]\[, options] )
34+
35+
Sorts an input [ndarray][@stdlib/ndarray/ctor] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions.
36+
37+
```javascript
38+
var array = require( '@stdlib/ndarray/array' );
39+
40+
var x = array( [ -1.0, 2.0, -3.0 ] );
41+
42+
var y = sort( x );
43+
// returns <ndarray>[ -3.0, -1.0, 2.0 ]
44+
45+
var bool = ( x === y );
46+
// returns true
47+
```
48+
49+
The function has the following parameters:
50+
51+
- **x**: input [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
52+
- **sortOrder**: sort order (_optional_). May be either a scalar value, string, or an [ndarray][@stdlib/ndarray/ctor] having a real-valued or "generic" [data type][@stdlib/ndarray/dtypes]. If provided an [ndarray][@stdlib/ndarray/ctor], the value must have a shape which is [broadcast-compatible][@stdlib/ndarray/base/broadcast-shapes] with the complement of the shape defined by `options.dims`. For example, given the input shape `[2, 3, 4]` and `options.dims=[0]`, an [ndarray][@stdlib/ndarray/ctor] sort order must have a shape which is [broadcast-compatible][@stdlib/ndarray/base/broadcast-shapes] with the shape `[3, 4]`. Similarly, when performing the operation over all elements in a provided input [ndarray][@stdlib/ndarray/ctor], an [ndarray][@stdlib/ndarray/ctor] sort order must be a zero-dimensional [ndarray][@stdlib/ndarray/ctor]. By default, the sort order is `1` (i.e., increasing order).
53+
- **options**: function options (_optional_).
54+
55+
The function accepts the following options:
56+
57+
- **dims**: list of dimensions over which to perform operation. If not provided, the function performs the operation over all elements in a provided input [ndarray][@stdlib/ndarray/ctor].
58+
59+
By default, the function sorts elements in increasing order. To sort in a different order, provide a `sortOrder` argument.
60+
61+
```javascript
62+
var array = require( '@stdlib/ndarray/array' );
63+
64+
var x = array( [ -1.0, 2.0, -3.0 ] );
65+
66+
var y = sort( x, -1.0 );
67+
// returns <ndarray>[ 2.0, -1.0, -3.0 ]
68+
```
69+
70+
In addition to numeric values, one can specify the sort order via one of the following string literals: `'ascending'`, `'asc'`, `'descending'`, or `'desc'`. The first two literals indicate to sort in ascending (i.e., increasing) order. The last two literals indicate to sort in descending (i.e., decreasing) order.
71+
72+
```javascript
73+
var array = require( '@stdlib/ndarray/array' );
74+
75+
var x = array( [ -1.0, 2.0, -3.0 ] );
76+
77+
// Sort in ascending order:
78+
var y = sort( x, 'asc' );
79+
// returns <ndarray>[ -3.0, -1.0, 2.0 ]
80+
81+
// Sort in descending order:
82+
y = sort( x, 'descending' );
83+
// returns <ndarray>[ 2.0, -1.0, -3.0 ]
84+
```
85+
86+
By default, the function performs the operation over all elements in a provided input [ndarray][@stdlib/ndarray/ctor]. To perform the operation over specific dimensions, provide a `dims` option.
87+
88+
```javascript
89+
var array = require( '@stdlib/ndarray/array' );
90+
91+
var x = array( [ -1.0, 2.0, -3.0, 4.0 ], {
92+
'shape': [ 2, 2 ],
93+
'order': 'row-major'
94+
});
95+
// returns <ndarray>[ [ -1.0, 2.0 ], [ -3.0, 4.0 ] ]
96+
97+
var y = sort( x, {
98+
'dims': [ 0 ]
99+
});
100+
// returns <ndarray>[ [ -3.0, 2.0 ], [ -1.0, 4.0 ] ]
101+
```
102+
103+
</section>
104+
105+
<!-- /.usage -->
106+
107+
<section class="notes">
108+
109+
## Notes
110+
111+
- The input [ndarray][@stdlib/ndarray/ctor] is sorted **in-place** (i.e., the input [ndarray][@stdlib/ndarray/ctor] is **mutated**).
112+
- If `sortOrder < 0.0` or is either `'desc'` or `'descending'`, the input [ndarray][@stdlib/ndarray/ctor] is sorted in **decreasing** order. If `sortOrder > 0.0` or is either `'asc'` or `'ascending'`, the input [ndarray][@stdlib/ndarray/ctor] is sorted in **increasing** order. If `sortOrder == 0.0`, the input [ndarray][@stdlib/ndarray/ctor] is left unchanged.
113+
- The algorithm distinguishes between `-0` and `+0`. When sorted in increasing order, `-0` is sorted before `+0`. When sorted in decreasing order, `-0` is sorted after `+0`.
114+
- The algorithm sorts `NaN` values to the end. When sorted in increasing order, `NaN` values are sorted last. When sorted in decreasing order, `NaN` values are sorted first.
115+
- The function iterates over [ndarray][@stdlib/ndarray/ctor] elements according to the memory layout of the input [ndarray][@stdlib/ndarray/ctor]. Accordingly, performance degradation is possible when operating over multiple dimensions of a large non-contiguous multi-dimensional input [ndarray][@stdlib/ndarray/ctor]. In such scenarios, one may want to copy an input [ndarray][@stdlib/ndarray/ctor] to contiguous memory before sorting.
116+
117+
</section>
118+
119+
<!-- /.notes -->
120+
121+
<section class="examples">
122+
123+
## Examples
124+
125+
<!-- eslint no-undef: "error" -->
126+
127+
```javascript
128+
var discreteUniform = require( '@stdlib/random/discrete-uniform' );
129+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
130+
var sort = require( '@stdlib/blas/ext/sort' );
131+
132+
// Generate an array of random numbers:
133+
var x = discreteUniform( [ 5, 5 ], -20, 20, {
134+
'dtype': 'generic'
135+
});
136+
console.log( ndarray2array( x ) );
137+
138+
// Perform operation:
139+
sort( x, {
140+
'dims': [ 0 ]
141+
});
142+
143+
// Print the results:
144+
console.log( ndarray2array( x ) );
145+
```
146+
147+
</section>
148+
149+
<!-- /.examples -->
150+
151+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
152+
153+
<section class="related">
154+
155+
</section>
156+
157+
<!-- /.related -->
158+
159+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
160+
161+
<section class="links">
162+
163+
[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor
164+
165+
[@stdlib/ndarray/dtypes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/dtypes
166+
167+
[@stdlib/ndarray/base/broadcast-shapes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/base/broadcast-shapes
168+
169+
</section>
170+
171+
<!-- /.links -->
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2026 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
// MODULES //
22+
23+
var bench = require( '@stdlib/bench' );
24+
var isnan = require( '@stdlib/math/base/assert/is-nan' );
25+
var pow = require( '@stdlib/math/base/special/pow' );
26+
var uniform = require( '@stdlib/random/array/uniform' );
27+
var ndarray = require( '@stdlib/ndarray/base/ctor' );
28+
var format = require( '@stdlib/string/format' );
29+
var pkg = require( './../package.json' ).name;
30+
var sort = require( './../lib' );
31+
32+
33+
// VARIABLES //
34+
35+
var options = {
36+
'dtype': 'float64'
37+
};
38+
39+
40+
// FUNCTIONS //
41+
42+
/**
43+
* Creates a benchmark function.
44+
*
45+
* @private
46+
* @param {PositiveInteger} len - array length
47+
* @returns {Function} benchmark function
48+
*/
49+
function createBenchmark( len ) {
50+
var x = uniform( len, -50.0, 50.0, options );
51+
x = new ndarray( options.dtype, x, [ len ], [ 1 ], 0, 'row-major' );
52+
53+
return benchmark;
54+
55+
/**
56+
* Benchmark function.
57+
*
58+
* @private
59+
* @param {Benchmark} b - benchmark instance
60+
*/
61+
function benchmark( b ) {
62+
var o;
63+
var i;
64+
65+
b.tic();
66+
for ( i = 0; i < b.iterations; i++ ) {
67+
o = sort( x, ( i%2 ) ? 1 : -1 );
68+
if ( typeof o !== 'object' ) {
69+
b.fail( 'should return an ndarray' );
70+
}
71+
}
72+
b.toc();
73+
if ( isnan( o.get( i%len ) ) ) {
74+
b.fail( 'should not return NaN' );
75+
}
76+
b.pass( 'benchmark finished' );
77+
b.end();
78+
}
79+
}
80+
81+
82+
// MAIN //
83+
84+
/**
85+
* Main execution sequence.
86+
*
87+
* @private
88+
*/
89+
function main() {
90+
var len;
91+
var min;
92+
var max;
93+
var f;
94+
var i;
95+
96+
min = 1; // 10^min
97+
max = 6; // 10^max
98+
99+
for ( i = min; i <= max; i++ ) {
100+
len = pow( 10, i );
101+
f = createBenchmark( len );
102+
bench( format( '%s:dtype=%s,len=%d', pkg, options.dtype, len ), f );
103+
}
104+
}
105+
106+
main();
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
2+
{{alias}}( x[, sortOrder][, options] )
3+
Sorts an input ndarray along one or more ndarray dimensions.
4+
5+
The algorithm distinguishes between `-0` and `+0`. When sorted in increasing
6+
order, `-0` is sorted before `+0`. When sorted in decreasing order, `-0` is
7+
sorted after `+0`.
8+
9+
The algorithm sorts `NaN` values to the end. When sorted in increasing
10+
order, `NaN` values are sorted last. When sorted in decreasing order, `NaN`
11+
values are sorted first.
12+
13+
The function sorts an input ndarray in-place and thus mutates an input
14+
ndarray.
15+
16+
Parameters
17+
----------
18+
x: ndarray
19+
Input array. Must have a real-valued or "generic" data type.
20+
21+
sortOrder: ndarray|number|string (optional)
22+
Sort order. May be either a scalar value, string, or an ndarray having a
23+
real-valued or "generic" data type. If provided an ndarray, the value
24+
must have a shape which is broadcast compatible with the complement of
25+
the shape defined by `options.dims`. For example, given the input shape
26+
`[2, 3, 4]` and `options.dims=[0]`, an ndarray sort order must have a
27+
shape which is broadcast compatible with the shape `[3, 4]`. Similarly,
28+
when performing the operation over all elements in a provided input
29+
ndarray, an ndarray sort order must be a zero-dimensional ndarray.
30+
31+
If specified as a string, must be one of the following values:
32+
33+
- ascending: sort in increasing order.
34+
- asc: sort in increasing order.
35+
- descending: sort in decreasing order.
36+
- desc: sort in decreasing order.
37+
38+
By default, the sort order is `1` (i.e., increasing order).
39+
40+
options: Object (optional)
41+
Function options.
42+
43+
options.dims: Array<integer> (optional)
44+
List of dimensions over which to perform operation. If not provided, the
45+
function performs the operation over all elements in a provided input
46+
ndarray.
47+
48+
Returns
49+
-------
50+
out: ndarray
51+
Input array.
52+
53+
Examples
54+
--------
55+
> var x = {{alias:@stdlib/ndarray/array}}( [ -1.0, 2.0, -3.0, -4.0 ] );
56+
> var y = {{alias}}( x )
57+
<ndarray>[ -4.0, -3.0, -1.0, 2.0 ]
58+
59+
See Also
60+
--------

0 commit comments

Comments
 (0)