java - How to sort two arrays according to one array's values -


public static void getsort(short[] time, string[] champs){     system.out.println("time     champs\n");     for(int a= 0; < time.length; a++){         char fletter=champs[a].charat(0);         if('b' == fletter){             arrays.sort(champs);             system.out.println(time[a] + "     " + champs[a]);         }     }     for(int a= 0; < time.length; a++){         char fletter=champs[a].charat(0);         if('c' == fletter){             arrays.sort(champs);             system.out.println(time[a] + "     " + champs[a]);         }     } } 

hi guys, i'm in need advice , on function. trying output , display inside arrays time , champs.

what desire output have is:

time----champs  2001 banana     2004 banana  2000 boat  2003 boat  2011 carrot  2013 carrot  2002 cucumber 

where time , champs displayed correctly being displayed alphabetically when use arrays.sort(champs);

my output is:

time----champs  2004  banana  2005  banana  2006  boat  2007  boat  2008  carrot  2009  carrot  2010  cucumber 

the output of champs displayed correctly years listed down going down 1.

and without arrays.sort(champs) output is:

time----champs  2000 boat  2001 banana    2003 boat  2004 banana  2002 cucumber  2011 carrot  2013 carrot 

which can see time correct champs not sorted alphabetically.

i think issue you're not re-ordering 'time' 'champs'. example, appears though 'time' years in increasing order, , champs whoever champion team year. when sort champs alphabetical order, they're out of sync time.

to solve this, need pair time champs if sort 1 of values, other moves it.

start internal class this:

public static class tuple implements comparable<tuple>{     public short time;     public string champ;      public tuple(short time, string champ) {         this.time = time;         this.champ = champ;     }      public int compareto(tuple other) {         return this.champ.compareto(other.champ);     } } 

then, change current method make array of tuples:

public static void getsort(short[] time, string[] champs){    // assuming time.length & champ.length same    tuple[] timechamps = new tuple[time.length];    (int = 0; < time.length; a++) {      timechamps[a] = new tuple(time[a], champs[a]);    } 

because we've made new tuple implement comparable, can sort it. compareto method of tuple sorts in alphabetical order properly.

   arrays.sort(timechamps); 

then can print out results

   (tuple t : timechamps) {      system.out.println(t.time+"\t"+t.champ);    }  } 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -