Question:
Need help sorting parallel array:
Double [] salary = {500.00, 200.00, 1000.00, 2500.00}; String [] name = {"Sam", "Dave", "Jake", "Ryan"};
Code:
public class Example { public static void main(String[] args) { // parallel array Double [] salary = {500.00, 200.00, 1000.00, 2500.00}; String [] name = {"Sam", "Dave", "Jake", "Ryan"}; System.out.println("Before:"); for (int n = 0; n < name.length; n++) { System.out.println(name[n] + ":" + salary[n]); } int remaining = salary.length - 1; for(int x = 0; x < (salary.length-1); x++) { for(int y = 0; y < (remaining); y++) { double tmp1; String tmp2; if ( salary[y] > salary[y+1] ) { tmp1 = salary[y+1]; salary[y+1] = salary[y]; salary[y] = tmp1; tmp2 = name[y+1]; name[y+1] = name[y]; name[y] = tmp2; } } remaining--; } System.out.println("After:"); for (int n = 0; n < name.length; n++) { System.out.println(name[n] + ":" + salary[n]); } } }
Output:
$ java Example Before: Sam:500.0 Dave:200.0 Jake:1000.0 Ryan:2500.0 After: Dave:200.0 Sam:500.0 Jake:1000.0 Ryan:2500.0