Sorting two arrays simultaneously

后端 未结 8 2143
终归单人心
终归单人心 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.

提交回复
热议问题