Best way to reorder multiple arrays from one sort key?

Hi folks,

So, as a learning project I’m working an interpolation tool, and one thing that came up to me is if the user inputs unsorted data (for whatever reason), instead of just returning an error, I might want an option to sort the data for them and continue. So, I looked at the zig std and its multiple sorting algorithms, but they all seem to operate on our array (let’s call it x) in-place or return a sorted copy of x. So, if I want to sort x and also perform the same swaps on my dependent variable array y, what’s the best approach:

  1. Zip them up in an array of structs and sort them via key value?
    a. If this is the way to go, as far as I know you’d wanna use a struct of arrays like MultiArrayList, but is there an easy way to sort those or would I still need glue logic?
  2. Just implement my own sort with heavy copy-paste from zig std that returns an index array telling how to make all the swaps?
  3. Is this exactly what the xContext() versions are for?

Okay, writing this made me actually look at the implementation of sort.zig, which in turn made me understand the context inputs better than I did from looking at the docs online, and it seems like (3) is indeed the answer with the context.swap() implementation referencing my data arrays, but I will still put up the question just in case the discussion is useful (or as a search result for future users).

1 Like

Hi @kitkat-24
The 3rd approch is the best.

std.sort.xContext functions accept a context that is expected to have two functions: lessThan and swap.

For usage examples, see the std.sort.x functions; they are implemented as a call to the std.sort.xContext functions. e.g. std.sort.heap

2 Likes