Search code examples
arraysalgorithmsortinglanguage-agnostic

What is the programming language agnostic term for synchronously sorting two arrays by the values of one of the arrays


Suppose we have two arrays:

a = [4,3,8,7]
b = [(1,2),(5,6),(8,6),(9,0)] 

So what we want now is, a sorting of the array a. So the result of the sorting should be a_sorted = [3,4,7,8] . And, we must not sort the array b. Instead, the order of array b must be changed according to the sorting order of array a.

So, array b must be b_sorted = [(5,6),(1,2),(9,0),(8,6)]

i.e., the order of a_sorted will be a_sorted = [a[1],a[0],a[3],a[2]]. Correspondingly, b_sorted = [b[1],b[0],b[3],b[2]]

The question is simpler. Is there a name for this kind of sorting? :


Solution

  • Actually, this kind of thing isn't really uncommon, although it's less prevalent today than it was in the past. It's an extension of the tag sort idea, where keys are sorted and then the corresponding records are read and written in order. You'd normally use a tag sort when:

    • There isn't enough memory to load all of the records you want to sort, but you can easily load the keys.

    OR

    • Moving large records around in memory during the sort is very expensive. Swapping the keys takes less time.

    The second one isn't really an issue very often these days, because you're usually sorting an array of references, meaning that the only things that get swapped around are pointers--4 bytes or 8 bytes each.

    Some APIs have built-in support for this type of parallel array sorting. For example, the .NET Array class has a Sort(array, array) method that works exactly like you describe.