Sort a parallel array using Arrays.sort()

前端 未结 5 1471
暗喜
暗喜 2020-11-30 15:41

Is it possible to sort an array using Arrays.sort() and thereafter have another related array positioned the same as the sorted array for example:



        
5条回答
  •  感动是毒
    2020-11-30 16:11

    It is possible to use the built-in Arrays.sort to archive the effect without creating a class for the parallel array content.

    Note that the index should be an object array, not primitive array. (Arrays.sort(int[]) does not take comparator)

    final int n = 10;
    int[] values = new int[n];
    Integer[] index = new Integer[n];
    par_foreach(n, i -> index[i] = i);
    par_foreach(n, i -> values[i] = random.nextInt(100));
    Arrays.sort(index, (a, b) -> Integer.compare(values[a], values[b]));
    println("values", values);
    println("index", index);
    print("ordered:");
    foreach(n, i -> print(" " + values[index[i]]));
    println();
    

    Remark

    foreach :: Num -> (Num -> void) (parallel) par_foreach :: Num -> (Num -> void) In case you cannot imagine the implementation: https://github.com/beenotung/javalib/blob/master/src/com/github/beenotung/javalib/Utils.java

提交回复
热议问题