Sorting two arrays simultaneously

后端 未结 8 2124
终归单人心
终归单人心 2020-12-01 17:29

I\'m learning and understanding Java now, and while practising with arrays I had a doubt. I wrote the following code as an example:



        
相关标签:
8条回答
  • 2020-12-01 18:21

    Some people propose making a product type. That is feasible only if the amount of elements is small. By introducing another object you add object overhead (30+ bytes) for each element and a performance penalty of a pointer (also worsening cache locality).

    Solution without object overhead

    Make a third array. Fill it with indices from 0 to size-1. Sort this array with comparator function polling into the array according to which you want to sort.

    Finally, reorder the elements in both arrays according to indices.

    Alternative solution

    Write the sorting algorithm yourself. This is not ideal, because you might make a mistake and the sorting efficiency might be subpar.

    0 讨论(0)
  • 2020-12-01 18:23

    The arrays are not linked in any way. Like someone pointed out take a look at

    SortedMap http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html

    TreeMap http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

    0 讨论(0)
提交回复
热议问题