繁体   English   中英

如何对两个 arrays 进行排序,其中一个是基于另一个排序的?

[英]How to sort two arrays with one being sorted based on the sorting of the other?

所以我经常遇到这个问题。 让我解释。 假设我有这两个 arrays: A1={1,2,3,4,5,6,7,8,9,10}; A2={1,2,3,0,2,1,1,0,0,0}; . 我需要的是:当我对 A2 进行排序时,无论在 A2 中发生什么交换和移动元素,在 A1 中也应该发生同样的事情。 基本上,我正在尝试使用两个 arrays 创建一个 Map,而不是创建一个实际的 HashMap 或 HashTable。

最后 arrays 应该如下所示: A1={4,8,9,10,1,6,7,2,5,3}; A2={0,0,0,0,1,1,1,2,2,3}; . arrays的对应值还是一样的,但是数据是按照A2排序的。 我需要一种方法以尽可能快的方式进行这种排序。

我为什么要这样做? 好吧,在一个问题中,给出了一个数字数组,我需要按照出现次数增加的顺序打印数组的所有数字。 假设 A1 表示给定数组中的数字,A2 表示相应数字的出现次数。 使用 arrays,我可以轻松地以上述方式对 arrays 进行排序,并使用索引遍历 A1 并打印数字。 有人可能会建议 HashMap 并对其进行排序,但它通过键访问值,因此我认为排序不会有很大意义。 我确信有更好的方法来实现我想要做的事情。 请提出一个好的排序方法或任何更好的方法来解决这个问题。 提前致谢!

配对 Class 可以在这里解决问题。

import java.util.*;
public class Main
{
    static class Pair implements Comparable<Pair>
    {
        int a1;
        int a2;
        Pair (int a1, int a2) //constructor 
        {
            this.a1 = a1;
            this.a2 = a2;
        }
        public int compareTo(Pair other) //making it only compare a2 values
        {
            return this.a2 - other.a2;
        }
    }
    public static void main(String[] args) 
    {
        int[] A1 = {1,2,3,4,5,6,7,8,9,10};
        int[] A2 = {1,2,3,0,2,1,1,0,0,0};
        Pair[] pairs = new Pair[A1.length];
        for (int i = 0; i < pairs.length; i++)
        {
            pairs[i] = new Pair(A1[i], A2[i]);
        }
        Arrays.sort(pairs);
        //printing values 
        for (int i = 0; i < A1.length; i++)
        {
            System.out.print(pairs[i].a1 + " ");
        }
        System.out.println();
        for (int i = 0; i < A2.length; i++)
        {
            System.out.print(pairs[i].a2 + " ");
        }
    }
}

通过制作包含 2 个变量a1a2的 Pair class ,您可以重写compareTo方法以仅比较a2值,这样当Arrays.sort被调用时,Pair 数组中的对将仅根据a2值交换. 然后,您可以访问对中的值并将它们打印出来。 这将产生您想要的 output。

您可以创建一个二维数组,其中每个元素都是长度为2的数组,并根据第二个元素对其进行排序。

int[] A1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, A2 = { 1, 2, 3, 0, 2, 1, 1, 0, 0, 0 };
final int[][] res = new int[A1.length][2];
for(int i = 0; i < res.length; i++) {
    res[i] = new int[] {A1[i], A2[i]};
}
Arrays.sort(res, (a,b)->Integer.compare(a[1], b[1]));
//Alternatively, Arrays.sort(res, Comparator.comparingInt(a -> a[1]));
for(final int[] a : res) {
    System.out.println(a[0] + " " + a[1]);
}

您可以尝试根据您实际拥有的数据创建 object。 在这种情况下,object 可能包含两个字段,数字和出现次数。 然后实现一个比较器以按出现字段进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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