Kwker

Kwker for Swift

A SwiftPM package over Kwker's C library (libkwker_c). It sorts, selects, partially sorts, argsorts and takes the top k of contiguous numeric collections in place. It also orders strings in a collation. The engine is chosen at run time: AVX-512, AVX2, NEON or portable.

SwiftAdd the Kwker Swift package (SwiftPM).
import Kwker

var a: [Double] = [3, -0.0, .nan, 1, 0]
a.kwkSort()                                   // [-0.0, 0.0, 1.0, 3.0, nan]
a.kwkSort(order: .descending)                 // NaNs stay last unless .nansFirst
let ix = a.kwkArgsort()                       // the stable sorting permutation
let (v, i) = a.kwkTopK(2)                     // the 2 smallest and their positions
var b = [Int32](repeating: 0, count: 1000)
b.kwkSelect(500)                              // b[500] in its sorted place
b[100..<200].kwkSort()                        // slices sort in place
let s = Kwker.sorted(strings: ["file10", "file2"], collation: .natural)  // ["file2", "file10"]
let e = Kwker.sorted(strings: names, collation: .ebcdic037)              // mainframe order

Key types: UInt8, Int8, UInt16, Int16, UInt32, Int32, Float, UInt64, Int64, Double, Int and UInt.

Collections: any MutableCollection of them. Collections with contiguous storage (Array, ArraySlice, ContiguousArray, unsafe buffers) are sorted where they are. Other collections are copied, sorted and written back.

Float order: total order. -0.0 sorts before +0.0, and NaNs go last unless .nansFirst is given.

Stability: argsort and top-k are stable, so equal keys keep their index order.

String collations:

Building

SwiftPM needs the C library's headers and library. Use the release package (include/, lib/), found through pkg-config (kwker.pc on PKG_CONFIG_PATH), or pass the paths:

ShellOn your machine.
swift build -c release -Xcc -I<prefix>/include -Xlinker -L<prefix>/lib -Xlinker -rpath -Xlinker <prefix>/lib
"$(swift build -c release --show-bin-path)/kwker-check"   # the checks + 1M timings against Array.sort()

The checks run in CI on the macOS runner (ss --ci 'bind:runners=macos,tests=swift'). They compare against Swift's own sorts: every key type and order, select, partial sort, stable argsort, top-k, a non-contiguous collection, slices and strings in each collation.