Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two arrays, one stores the distance of the cities and the other stores the corresponding population. Everything works fine if the distance of the cities is in ascending order. But let say if someone inputs the distance randomly. How can I sort the cities array and also make sure that the population of the respective city is in the same index as the index of its respective city population.

For example:

  • City 1 has population 333
  • City 3 has population 33333
  • City 5 has population 33
int[] city = {1, 3, 5};
int[] pop  = {333, 33333, 33};

Everything works fine because the city array is sorted already.

But when I input:

int[] city = {3, 1, 5};
int[] pop  = {3333, 333, 33};

Big problem!

I want sort the array city and make sure that the population array has all its elements at the same index as their respective city.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
103 views
Welcome To Ask or Share your Answers For Others

1 Answer

The good way of doing this is having a city class:

class City{
    private int id;
    private long population;

    //... getters, setters, etc
}

a city comparator class:

class CityPopulationComparator implements Comparator<City> {
    @Override
    public int compare(City c1, City c2) {
        return Long.compare(c1.getPopulation(), c2.getPopulation());
    }
}

And an array list of cities:

ArrayList<City> cities;

and finally sort it using:

Collections.sort(cities, new CityPopulationComparator());

But if you need to have your cities and populations this way, you can write a sort method yourself (a bubble sort for example) and whenever you swap two cities, also swap corresponding pupulations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...