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

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

问题描述

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

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};

一切正常,因为城市数组已经排序.

Everything works fine because the city array is sorted already.

但是当我输入时:

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

大问题!

我想对数组 city 进行排序,并确保人口数组的所有元素都与它们各自的城市位于相同的索引处.

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天全站免登陆