Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting two arrays...

 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
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
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic