排序两个并行数组 [英] Sorting two parallel arrays

查看:90
本文介绍了排序两个并行数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,一个数组存储城市的距离,另一个数组存储相应的人口.如果城市的距离按升序排列,则一切正常.但可以说是否有人随机输入距离.如何对城市数组进行排序,并确保各个城市的人口与其城市人口的索引处于同一索引中.

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.

例如:

  • 城市1的人口333
  • 城市3的人口为33333
  • 城市5的人口为33
int[] city = {1, 3, 5};
int[] pop  = {333, 33333, 33};

一切都很好,因为已经对city数组进行了排序.

Everything works fine because the city array is sorted already.

但是当我输入:

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

大问题!

我要对数组城市进行排序,并确保人口数组的所有元素与其各自的城市在同一索引处.

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.

推荐答案

做到这一点的好方法是开设一个城市班级:

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

class City{
    private int id;
    private long population;

    //... getters, setters, etc
}

城市比较类:

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

以及城市列表:

ArrayList<City> cities;

最后使用:

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.

这篇关于排序两个并行数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆