开发者

Curious Case of Sorting two arrays in tandem

S开发者_C百科uppose 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? :


You're just finding the sort permutation of one array ( [2,1,4,3] for a) and applying it to the other. Many languages handle this well.

For example, in Matlab, you can call [sortedA, sortedBy] = sort([4 3 8 7]); Then sortedA = a(sortedBy) = [3 4 7 8] and sortedBy = [2 1 4 3], so your new b will be b(sortBy).


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.


I don't think there's a name for such a thing. Note that such "parallel arrays" is usually frowned upon, and often used by people (students) new to programming who haven't been taught how to use classes properly (no offense meant). If there is a relation between the two arrays, they should be put in some sort of object, and then that object should be sorted instead.

It all depends on the situation, of course. One might be using a language that hasn't the ability to group related attributes in (custom) objects.


Add the values of b to the keys of a so that you get a multidimensional array. Then sort that array.


Yeah in PHP there is an array sorting function called array_multisort which does what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜