Is it possible to sort an array using Arrays.sort()
and thereafter have another related array positioned the same as the sorted array for example:
String arrNames[] = new String[5];
String arrCellNo[] = new String[arrNames.length];
String arrNamesSorted[] = new String[arrNames.length];
System.arraycopy(arrNames, 0, arrNamesSorted, 0, arrNames.length);
Arrays.sort(arrNamesSorted);
From this point what i would like to do is sort the CellNo
array such that if "person" had a cellNo "x", he will have the same "cellNo" "x" after the array arrNames
is sorted
It is possible to use the built-in Arrays.sort to archive the effect without creating a class for the parallel array content.
Note that the index should be an object array, not primitive array. (
Arrays.sort(int[])
does not take comparator)Remark
foreach :: Num -> (Num -> void) (parallel) par_foreach :: Num -> (Num -> void)
In case you cannot imagine the implementation: https://github.com/beenotung/javalib/blob/master/src/com/github/beenotung/javalib/Utils.javaI found some of the concepts introduced in the answers hard to grasp therefore in my own solution resorted to undesirable programming methods as a trade of for code easier to understand and created a bubble sort method and at the end manipulated the second array like so :
You can't have
Arrays.sort
manipulate a second array the way it's sorting the first array.The solution is to sort your own objects that contain all the data you need. Create a
Contact
class with name and cell number attributes. Then create a class that implementsComparator<Contact>
(say,ContactComparator
) to compare the names.Then you will be able to sort an array of
Contact
objects with a particular overload ofArrays.sort
.All data will remain organized, in that the same name will still have the same cell number.
I would go for a different approach:
Create a new object:
Create a comparator:
Call
Array.sort(persons, new MyComparator())
on aPerson[] persons = ...
arrayIf names will be unique, consider using a SortedMap: