This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Sorting two arrays... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting two arrays..." Watch "Sorting two arrays..." New topic

Sorting two arrays...

James Palmer
Ranch Hand

Joined: Mar 15, 2004
Posts: 36
Basically my problem is i have two arrays,numbers(from 1 to 10) and persons. For each person there is an individual number and as both arrays already have their variables i want to put the numbers in descending order.The problem is that by sorting the numbers,i dont know how to sort the names at the same time to stick with their individual numbers.For example:
String[] names = {John, Andy};
int[] scores = {7,3};

By sorting the scores here they will become {3,7} so the 3 will be the first element of the array and it will go with John instead of Andy,which is what i would wish to do.Any ideas?Thanks
Tom Hill
Ranch Hand

Joined: Aug 24, 2003
Posts: 115
It's probably best to store the name and number that correspond to each other as an object. Then write a compareTo() method which returns values corresponding to how the objects compare eg: -1 less than, 0 greater than, 1 more than. So:

Then sort an array of PersonNumber Objects i guess.
[ July 22, 2004: Message edited by: Tom Hill ]
Tom Hill
Ranch Hand

Joined: Aug 24, 2003
Posts: 115
A Hack and Slah way to do it would be: if you have array A of ints: and array B of names (Strings).
When your sorting algorithms swaps the locations of 2 ints (i assume via an empty variable?) that at the same time you swap the strings on the names: So:

I dont like this very much though - it is not as neat at the alternative solution. Ive probably made some mistake in there too
I agree. Here's the link:
subject: Sorting two arrays...
Similar Threads
Problem with parallel arrays when sorting in decending order
Sorting JTree Nodes alphabetically
Descending order and associating Array Elements in sort method to another's elements
Sorting a row in a two deminsional array
Does arraycopy create aliases?