Sort the time array and swap position of element in both the array together, in that way when ever swap happens it will maintain the link between times and names array, here is the program for that, I did sorting in descending Order
public static void main(String[] args){
String[] names = { "Paul", "Dan", "Hayden", "Sam", "Pauline"};
int[] times = { 341, 273, 278, 329, 445 };
for(int outerIndex = 0; outerIndex < times.length; outerIndex++){
for(int innerIndex = outerIndex+1; innerIndex < times.length; innerIndex++){
if(times[outerIndex]<times[innerIndex]){
swap(outerIndex, innerIndex, names, times);
}
}
}
}
Here I am swaping element position in both the arrays:
public static void swap(int outerIndex, int innerIndex, String[] names, int[] times){
int tempTime;
String tempName;
tempTime = times[outerIndex];
tempName = names[outerIndex];
times[outerIndex] = times[innerIndex];
names[outerIndex] = names[innerIndex];
times[innerIndex] = tempTime;
names[innerIndex] = tempName;
}
Input:
String[] names = { "Paul", "Dan", "Hayden", "Sam", "Pauline"};
int[] times = { 341, 273, 278, 329, 445 };
Output:
String[] names = {"Pauline", "Paul", "Sam", "Hayden", "Dan"};
int[] times = { 445, 341, 329, 278, 273};