Skip to content

Commit bff3c1e

Browse files
headlessNodekgryte
andauthored
feat: add blas/ext/sorthp
PR-URL: #8098 Ref: #2656 Closes: stdlib-js/metr-issue-tracker#77 Co-authored-by: Athan Reines <[email protected]> Reviewed-by: Athan Reines <[email protected]>
1 parent d3aa7cd commit bff3c1e

File tree

12 files changed

+2706
-0
lines changed

12 files changed

+2706
-0
lines changed
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2025 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+
# sorthp
22+
23+
> Sort an input [ndarray][@stdlib/ndarray/ctor] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions using heapsort.
24+
25+
<section class="usage">
26+
27+
## Usage
28+
29+
```javascript
30+
var sorthp = require( '@stdlib/blas/ext/sorthp' );
31+
```
32+
33+
#### sorthp( x\[, sortOrder]\[, options] )
34+
35+
Sorts an input [ndarray][@stdlib/ndarray/ctor] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions using heapsort.
36+
37+
```javascript
38+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
39+
var array = require( '@stdlib/ndarray/array' );
40+
41+
var x = array( [ -1.0, 2.0, -3.0 ] );
42+
43+
var y = sorthp( x );
44+
// returns <ndarray>
45+
46+
var arr = ndarray2array( y );
47+
// returns [ -3.0, -1.0, 2.0 ]
48+
49+
var bool = ( x === y );
50+
// returns true
51+
```
52+
53+
The function has the following parameters:
54+
55+
- **x**: input [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
56+
- **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).
57+
- **options**: function options (_optional_).
58+
59+
The function accepts the following options:
60+
61+
- **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].
62+
63+
By default, the function sorts elements in increasing order. To sort in a different order, provide a `sortOrder` argument.
64+
65+
```javascript
66+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
67+
var array = require( '@stdlib/ndarray/array' );
68+
69+
var x = array( [ -1.0, 2.0, -3.0 ] );
70+
71+
var y = sorthp( x, -1.0 );
72+
// returns <ndarray>
73+
74+
var arr = ndarray2array( y );
75+
// returns [ 2.0, -1.0, -3.0 ]
76+
```
77+
78+
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.
79+
80+
```javascript
81+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
82+
var array = require( '@stdlib/ndarray/array' );
83+
84+
var x = array( [ -1.0, 2.0, -3.0 ] );
85+
86+
// Sort in ascending order:
87+
var y = sorthp( x, 'asc' );
88+
// returns <ndarray>
89+
90+
var arr = ndarray2array( y );
91+
// returns [ -3.0, -1.0, 2.0 ]
92+
93+
// Sort in descending order:
94+
y = sorthp( x, 'descending' );
95+
// returns <ndarray>
96+
97+
arr = ndarray2array( y );
98+
// returns [ 2.0, -1.0, -3.0 ]
99+
```
100+
101+
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.
102+
103+
```javascript
104+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
105+
var array = require( '@stdlib/ndarray/array' );
106+
107+
var x = array( [ -1.0, 2.0, -3.0, 4.0 ], {
108+
'shape': [ 2, 2 ],
109+
'order': 'row-major'
110+
});
111+
112+
var v = ndarray2array( x );
113+
// returns [ [ -1.0, 2.0 ], [ -3.0, 4.0 ] ]
114+
115+
var y = sorthp( x, {
116+
'dims': [ 0 ]
117+
});
118+
// returns <ndarray>
119+
120+
v = ndarray2array( y );
121+
// returns [ [ -3.0, 2.0 ], [ -1.0, 4.0 ] ]
122+
```
123+
124+
</section>
125+
126+
<!-- /.usage -->
127+
128+
<section class="notes">
129+
130+
## Notes
131+
132+
- The input [ndarray][@stdlib/ndarray/ctor] is sorted **in-place** (i.e., the input [ndarray][@stdlib/ndarray/ctor] is **mutated**).
133+
- 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.
134+
- 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`.
135+
- 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.
136+
- The algorithm has space complexity `O(1)` and time complexity `O(N log2 N)`.
137+
- The algorithm is **unstable**, meaning that the algorithm may change the order of [ndarray][@stdlib/ndarray/ctor] elements which are equal or equivalent (e.g., `NaN` values).
138+
- 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.
139+
140+
</section>
141+
142+
<!-- /.notes -->
143+
144+
<section class="examples">
145+
146+
## Examples
147+
148+
<!-- eslint no-undef: "error" -->
149+
150+
```javascript
151+
var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
152+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
153+
var ndarray = require( '@stdlib/ndarray/ctor' );
154+
var sorthp = require( '@stdlib/blas/ext/sorthp' );
155+
156+
// Generate an array of random numbers:
157+
var xbuf = discreteUniform( 25, -20, 20, {
158+
'dtype': 'generic'
159+
});
160+
161+
// Wrap in an ndarray:
162+
var x = new ndarray( 'generic', xbuf, [ 5, 5 ], [ 5, 1 ], 0, 'row-major' );
163+
console.log( ndarray2array( x ) );
164+
165+
// Perform operation:
166+
sorthp( x, {
167+
'dims': [ 0 ]
168+
});
169+
170+
// Print the results:
171+
console.log( ndarray2array( x ) );
172+
```
173+
174+
</section>
175+
176+
<!-- /.examples -->
177+
178+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
179+
180+
<section class="related">
181+
182+
</section>
183+
184+
<!-- /.related -->
185+
186+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
187+
188+
<section class="links">
189+
190+
[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor
191+
192+
[@stdlib/ndarray/dtypes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/dtypes
193+
194+
[@stdlib/ndarray/base/broadcast-shapes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/base/broadcast-shapes
195+
196+
</section>
197+
198+
<!-- /.links -->
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2025 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 pkg = require( './../package.json' ).name;
29+
var sorthp = require( './../lib' );
30+
31+
32+
// VARIABLES //
33+
34+
var options = {
35+
'dtype': 'float64'
36+
};
37+
38+
39+
// FUNCTIONS //
40+
41+
/**
42+
* Creates a benchmark function.
43+
*
44+
* @private
45+
* @param {PositiveInteger} len - array length
46+
* @returns {Function} benchmark function
47+
*/
48+
function createBenchmark( len ) {
49+
var x = uniform( len, -50.0, 50.0, options );
50+
x = new ndarray( options.dtype, x, [ len ], [ 1 ], 0, 'row-major' );
51+
52+
return benchmark;
53+
54+
/**
55+
* Benchmark function.
56+
*
57+
* @private
58+
* @param {Benchmark} b - benchmark instance
59+
*/
60+
function benchmark( b ) {
61+
var o;
62+
var i;
63+
64+
b.tic();
65+
for ( i = 0; i < b.iterations; i++ ) {
66+
o = sorthp( x, ( i%2 ) ? 1 : -1 );
67+
if ( typeof o !== 'object' ) {
68+
b.fail( 'should return an ndarray' );
69+
}
70+
}
71+
b.toc();
72+
if ( isnan( o.get( i%len ) ) ) {
73+
b.fail( 'should not return NaN' );
74+
}
75+
b.pass( 'benchmark finished' );
76+
b.end();
77+
}
78+
}
79+
80+
81+
// MAIN //
82+
83+
/**
84+
* Main execution sequence.
85+
*
86+
* @private
87+
*/
88+
function main() {
89+
var len;
90+
var min;
91+
var max;
92+
var f;
93+
var i;
94+
95+
min = 1; // 10^min
96+
max = 6; // 10^max
97+
98+
for ( i = min; i <= max; i++ ) {
99+
len = pow( 10, i );
100+
f = createBenchmark( len );
101+
bench( pkg+':dtype='+options.dtype+',len='+len, f );
102+
}
103+
}
104+
105+
main();
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
2+
{{alias}}( x[, sortOrder][, options] )
3+
Sorts an input ndarray along one or more ndarray dimensions using heapsort.
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 algorithm has space complexity O(1) and time complexity O(N log2 N).
14+
15+
The algorithm is *unstable*, meaning that the algorithm may change the order
16+
of ndarray elements which are equal or equivalent (e.g., `NaN` values).
17+
18+
The function sorts an input ndarray in-place and thus mutates an input
19+
ndarray.
20+
21+
Parameters
22+
----------
23+
x: ndarray
24+
Input array. Must have a real-valued or "generic" data type.
25+
26+
sortOrder: ndarray|number|string (optional)
27+
Sort order. May be either a scalar value, string, or an ndarray having a
28+
real-valued or "generic" data type. If provided an ndarray, the value
29+
must have a shape which is broadcast compatible with the complement of
30+
the shape defined by `options.dims`. For example, given the input shape
31+
`[2, 3, 4]` and `options.dims=[0]`, an ndarray sort order must have a
32+
shape which is broadcast compatible with the shape `[3, 4]`. Similarly,
33+
when performing the operation over all elements in a provided input
34+
ndarray, an ndarray sort order must be a zero-dimensional ndarray.
35+
36+
If specified as a string, must be one of the following values:
37+
38+
- ascending: sort in increasing order.
39+
- asc: sort in increasing order.
40+
- descending: sort in decreasing order.
41+
- desc: sort in decreasing order.
42+
43+
By default, the sort order is `1` (i.e., increasing order).
44+
45+
options: Object (optional)
46+
Function options.
47+
48+
options.dims: Array<integer> (optional)
49+
List of dimensions over which to perform operation. If not provided, the
50+
function performs the operation over all elements in a provided input
51+
ndarray.
52+
53+
Returns
54+
-------
55+
out: ndarray
56+
Input array.
57+
58+
Examples
59+
--------
60+
> var x = {{alias:@stdlib/ndarray/array}}( [ -1.0, 2.0, -3.0, -4.0 ] );
61+
> var y = {{alias}}( x );
62+
> {{alias:@stdlib/ndarray/to-array}}( y )
63+
[ -4.0, -3.0, -1.0, 2.0 ]
64+
65+
See Also
66+
--------

0 commit comments

Comments
 (0)