简体   繁体   中英

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; a < 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; a < 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 for some advice and help on this function. What I am trying to do is output and display what is inside the arrays time and champs.

What my desire output is to have is:

Time----Champs

2001 Banana   

2004 Banana

2000 Boat

2003 Boat

2011 Carrot

2013 Carrot

2002 Cucumber

Where the time and champs are displayed correctly being displayed alphabetically But when I 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 is displayed correctly but the years are listed down going down by 1.

And without the Arrays.sort(champs) my output is:

Time----Champs

2000 Boat

2001 Banana  

2003 Boat

2004 Banana

2002 Cucumber

2011 Carrot

2013 Carrot

Which as you can see the time is correct with the champs but not sorted alphabetically.

I think your issue is that you're not re-ordering the 'time' with the 'champs'. From your example, it appears as though 'time' is just years in increasing order, and champs is whoever the champion team was for that year. When you sort the Champs into alphabetical order, they're out of sync with the time.

To solve this, you need to pair Time with Champs so that if you sort by one of the values, the other moves with it.

Start with an internal class like 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, where change your current method to make an array of Tuples:

public static void getSort(short[] time, String[] champs){
   // assuming time.length & champ.length are the same
   Tuple[] timechamps = new Tuple[time.length];
   for (int a = 0; a < time.length; a++) {
     timechamps[a] = new Tuple(time[a], champs[a]);
   }

because we've made the new tuple implement Comparable, we can simply sort it. The compareTo method of the tuple sorts in alphabetical order properly.

   Arrays.sort(timechamps);

Then you can print out the results

   for (Tuple t : timechamps) {
     System.out.println(t.time+"\t"+t.champ);
   }
 }

Would you like to have a look here http://www.mkyong.com/java/how-to-sort-a-map-in-java/

Here Key -----> champs Values --> time

I think you want to short your champs and time should be maintained with corresponding values. Hope its helpful to you.

It is better to create a Class and implement Comparable method

public class TimeChamp implements Comparable<TimeChamp>{

private short time;
private String champs;

public short getTime() {
    return time;
}

public void setTime(short time) {
    this.time = time;
}

public String getChamps() {
    return champs;
}

public void setChamps(String champs) {
    this.champs = champs;
}

@Override
public int compareTo(TimeChamp o) {
    if(getChamps().compareTo(o.getChamps())==0)
    {
        if(getTime()<o.getTime())
            return -1;
        else
            return 1;
    }
    else
        return getChamps().compareTo(o.getChamps());
}
}

Then you can create the function which will sort in your class like this

public void getSort(TimeChamp[] timeChamp)
{
    Arrays.sort(timeChamp);
    for(int i=0;i<timeChamp.length;i++)
    {   
        System.out.print(timeChamp[i].getTime());
        System.out.print("            ");
        System.out.println(timeChamp[i].getChamps());
    }
}

EDIT : Writing a more descriptive answer which constructs the data sets and calls the sort method

import java.util.Arrays;


public class MainExample {

/**
 * @param args
 */
public static void main(String[] args) {
            //Construct data sets
    TimeChamp [] timeChampArray = new TimeChamp[3];
    TimeChamp timeChamp = new TimeChamp();
    timeChamp.setChamps("Boat");
    timeChamp.setTime((short)2001);
    timeChampArray[0]=timeChamp;
    timeChamp= new TimeChamp();
    timeChamp.setChamps("Banana");
    timeChamp.setTime((short)2000);
    timeChampArray[1]=timeChamp;
    timeChamp= new TimeChamp();
    timeChamp.setChamps("Banana");
    timeChamp.setTime((short)2001);
    timeChampArray[2]=timeChamp;
            //Call the sort method
    new MainExample().getSort(timeChampArray);
}
//the sorting method
public void getSort(TimeChamp[] timeChamp)
{
    Arrays.sort(timeChamp);
    for(int i=0;i<timeChamp.length;i++)
    {   
        System.out.print(timeChamp[i].getTime());
        System.out.print("            ");
        System.out.println(timeChamp[i].getChamps());
    }
}

}

I also had a go. This is a fully functional, self-contained solution.

import java.util.Arrays;

public class TimeAndChampSorter {

    public static void main(String[] args) {
        // prepare input
        short[] time = { 2000, 2001, 2003, 2004, 2002, 2011, 2013 };
        String[] champs = { "Boat", "Banana", "Boat", "Banana", "Cucumber",
                "Carrot", "Carrot" };
        printSorted(time, champs);
    }

    public static void printSorted(short[] time, String[] champs) {
        // check arguments are of equal length
        if (time.length != champs.length) {
            throw new IllegalArgumentException(
                    "arrays time and champs must have equal length");
        }
        Tuple[] tuples = createTuples(time, champs);
        Arrays.sort(tuples);
        printTuples(tuples);
    }

    private static Tuple[] createTuples(short[] time, String[] champs) {
        // create empty array of Tuples with correct length
        Tuple[] tuples = new Tuple[champs.length];
        // fill the tuples array
        for (int i = 0; i < champs.length; i++) {
            tuples[i] = new Tuple(time[i], champs[i]);
        }
        return tuples;
    }

    private static void printTuples(Tuple[] tuples) {
        System.out.println("Time     Champs\n");
        for (Tuple tuple : tuples) {
            System.out.println(tuple);
        }
    }

    // static class to avoid having to create an instance of TimeAndChampSorter
    static class Tuple implements Comparable<Tuple> {
        short time;
        String champ;

        Tuple(short time, String champ) {
            // make sure champ is not null to avoid having to test for nulls in
            // compareTo
            if (champ == null) {
                throw new IllegalArgumentException("champ can not be null");
            }
            this.time = time;
            this.champ = champ;
        }

        // method of Comparable interface determines the ordering
        @Override
        public int compareTo(Tuple other) {
            return this.champ.compareTo(other.champ);
        }

        @Override
        public String toString() {
            return time + "     " + champ;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM