Kwker

Sorting keys with values

A key-value sort orders one array, the keys, and moves the matching entries of a second array, the values, along with them, in one call and without building an order array first.

Sort keys and values together

sort_kv(keys, values) sorts both arrays in place. values[i] stays with keys[i].

import numpy as np
import kwker

order_id = np.array([1042, 1007, 1093, 1001], dtype=np.uint32)
amount = np.array([25.0, 99.5, 12.75, 40.0])
kwker.sort_kv(order_id, amount)
print(order_id)
print(amount)
[1001 1007 1042 1093]
[40.   99.5  25.   12.75]

Keep equal keys in order: the stable sort

By default, values with equal keys may end up in any order among themselves. That is the fastest choice. Ask for the stable sort to keep them in their original order: stable=True in Python, sort_kv_stable in Rust, C and C++, and { stable: true } in JavaScript.

import numpy as np
import kwker

day = np.array([3, 1, 3, 2, 1], dtype=np.uint32)
event = np.array([30, 10, 31, 20, 11], dtype=np.int64)
kwker.sort_kv(day, event, stable=True)
print(day)
print(event)
[1 1 2 3 3]
[10 11 20 30 31]

Only the first k pairs

partial_sort_kv(keys, values, k) puts the k smallest keys first, in order, each with its value (the k largest in a descending order). select_kv is the key-value form of select.

import numpy as np
import kwker

latency = np.array([120, 85, 430, 95, 610], dtype=np.uint32)
request = np.array([1, 2, 3, 4, 5], dtype=np.int32)
kwker.partial_sort_kv(latency, request, 2, descending=True)
print(latency[:2], request[:2])
[610 430] [5 3]

Value types

Values can be any type of 1, 2, 4, 8, 12, 16, 24 or 32 bytes, structs and NumPy structured records included: C takes the value size in bytes, C++ and Rust take any trivially copyable (Copy) value type, and JavaScript any typed array of 1, 2, 4 or 8 bytes per element. Keys can be any integer or float type.