combining two sorted arrays while keeping track of individual indexes in java?
I have two pair of arrays. In each pair one array contains the index values referring to another result array while 2nd array contains the score. These are sorted, so that for example in pair one, i can select the 3 best high scores from Array-2 and they will correspond to indexes no 3,7 and 4 resp开发者_运维问答ectively.
Now the idea is to combine such pairs e.g Pair-1 and Pair-2, sort them and then select 3 best values.
Like if you see the picture below, in the sorted value array in result the first two highest values correspond to index number 1&6 in array from Pair-2 while 3rd value correspond to index 3 of array from Pair-1.It would be nice if you could give me some idea about how can i keep track of index numbers of respective arrays in the sorted result. I know how to sort them but really don't know how to go about keeping track of these individual arrays.
Think in objects.
If you create a Pair
object that has index, value and source array properties you can make it Comparable
on the value.
Create Pair
objects from your arrays, put them in a List
then sort it.
Have you tried Hashtable?
Hashtable<Integer, Pair> sortedTable = new Hashtable<Integer, Pair>();
for (int i = 0; i < firstArray.length; i++) { //if the 2 arrays are equal in length
sortedTable.put(sortedTable.size(), new Pair(firstArray[i], secondArray[i]));
}
精彩评论