Java:根据另一个数组的索引顺序对数组进行排序

时间:2020-07-27 19:24:26

标签: java arrays sorting indexing

在Java中,如何根据另一个排序数组的索引顺序对数组排序?例如,如果我有:

arr1 = {26, 8, 3}
arr2 = {3, 1, 2}
arr3 = {57, 23, 11}
arr4 = {78, 2, 61}

然后我将arr2升序排序

arr2 = {1, 2, 3}

然后我希望另一个成为:

arr1 = {8, 3, 26}
arr3 = {23, 11, 57}
arr4 = {2, 61, 78}

我该如何完成Java?我知道我会将新排序的数组保存到新实例中。有什么帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

这是一种实现方法。

  • 根据数组内容对目标数组的索引进行排序。
  • 然后使用该索引数组基于被索引的数组来映射所有数组。
Integer[] indices = IntStream.range(0, arr2.length)
        .boxed()                 
        .sorted(Comparator.comparing(i -> arr2[i]))        
        .toArray(Integer[]::new);
                          
List<int[]> list = Stream
        .of(arr1, arr2, arr3, arr4).map(arr -> Stream
                .of(indices)
                .mapToInt(i -> arr[i])
                .toArray())
        .collect(Collectors.toList());
        
list.forEach(arr -> System.out.println(Arrays.toString(arr))); 

打印

[8, 3, 26]
[1, 2, 3]
[23, 11, 57]
[2, 61, 78]

您还可以将这些数组放置在另一个"2D"数组中,并按照以下步骤进行操作,得到相同的结果。

int[][] arrays = { arr1, arr2, arr3, arr4 };

List<int[]> list = Arrays
        .stream(arrays)
        .map(arr -> Stream
                .of(indices)
                .mapToInt(i -> arr[i])
                .toArray())
        .collect(Collectors.toList());

答案 1 :(得分:0)

在其他地方找到答案

public class SortTogether{

    // sort the array a, and also update the elements in array b, c, and d
    // based on the index of a
    public static void bubbleSort(int[] a, int[] b, int[] c, int[] d) {

        for(int i=0; i<a.length; i++){
            for(int j=0; j<a.length-i-1;j++){
                if(a[j]>a[j+1]){
                    // when you are swapping the elements
                    int t = a[j]; a[j]=a[j+1];a[j+1]=t;
                    // swap the elements in the other arrays as well
                    // so the elements in other array will also stay together
                    t = b[j]; b[j]=b[j+1];b[j+1]=t;
                     t = c[j]; c[j]=c[j+1];c[j+1]=t;
                    t = d[j]; d[j]=d[j+1];d[j+1]=t;
                }
            }
        }

    }


    public static void main(String a[]) {
        int[] arr1 = {26, 8, 3};
        int[] arr2 = {3, 1, 2};
        int[] arr3 = {57, 23, 11};
        int[] arr4 = {78, 2, 61};
        System.out.println("Before sort");
        display(arr1);
        display(arr2);
        display(arr3);
        display(arr4);

        bubbleSort(arr2,arr1,arr3,arr4);

        System.out.println("\nAfter sort");
        display(arr1);
        display(arr2);
        display(arr3);
        display(arr4);

    }



    public static void display(int[] arr) {

        for (int num : arr) System.out.printf("%4d", num);
        System.out.println();
    }
}