如何按索引对数组进行排序? (SortIndex)

时间:2011-11-27 16:20:48

标签: java arrays

我有long[]的值。我需要的是有一个排序数组,其中包含我的第一个数组的索引。

例如:

INPUT:

long[ ] values = {1 , 3 , 2 , 5 , 4};

输出:

long[ ] SortIndex = {0 , 2 , 1 , 4 , 3}

表示:

values[0] < values[2] < values[1] < values[4] < values[3] 

... SortIndex的降序或升序并不重要。

4 个答案:

答案 0 :(得分:5)

long[] values = {1 , 3 , 2 , 5 , 4};
Map<Long, Integer> indices = new HashMap<Long, Integer>();
for (int index = 0; index < values.length; index++) {
    indices.put(values[index], index);
}

long[] copy = Arrays.copyOf(values, values.length);
Arrays.sort(copy);
for (int index = 0; index < copy.length; index++) {
    copy[index] = indices.get(copy[index]);
}

您的索引列表将位于copy

这里的工作示例:http://ideone.com/A9Imz

答案 1 :(得分:3)

您可以通过将Long对添加到TreeMap来实现此目的,其中密钥为values[index],值为index

遍历地图iterator将产生sortindex值。

<强>更新

看到没有接受的答案,以下是对此答案的评论后续跟进的代码。

    long[] values = { 1 , 3 , 2 , 5 , 4 };
    int[]  output = new int[values.length];

    Map<Long, Integer> map = new TreeMap<Long, Integer>();

    for (int n = 0; n < values.length; n++) {
        map.put(values[n] * values.length + n, n);
    }

    int n = 0;

    for (Integer index: map.values()) {
        output[n++] = index;
    }

    System.out.println(Arrays.toString(output));

输出:

[0, 2, 1, 4, 3]

当重复项是输入的一部分时,解决方案也可以工作:

long[] values = { 8, 5, 3, 2, 1, 1 };

输出:

[4, 5, 3, 2, 1, 0]

如果允许将sortOrder数组作为Integer数组接收,则第二个循环可以替换为:

Integer[] output = map.values().toArray(new Integer[values.length]);

答案 2 :(得分:1)

一个简单的想法是在每次迭代中找到最小值的索引,然后在该索引中放入一个较大的值。即使存在重复,这也会有效。 例如:

long[] values = { 1, 3, 2, 5, 4 };

long[] indices = new long[values.length];
for (int i = 0; i < values.length; i++) {
    long min = Long.MAX_VALUE;
    int minIndex = 0;
    for (int j = 0; j < values.length; j++) {
        if (min > values[j]) {
            minIndex = j;
            min = values[j];
        }
    }
    values[minIndex] = Long.MAX_VALUE;
    indices[i] = minIndex;
}

System.out.println(Arrays.toString(indices));

答案 3 :(得分:0)

我通过使用java Comparator接口找到了另一个优雅的解决方案。它也可以在值不唯一时使用:

final Long[] values = { 1, 3, 2, 5, 4, 2};
Integer[] indices = new Integer[values.length];
for (int i = 0; i < indices.length; i++) {
    indices[i] = i;
}
Comparator<Integer> comparator = new Comparator<Integer>() {
    @Override
    public int compare(Integer arg0, Integer arg1) {
        return values[arg0].compareTo(values[arg1]);
    }
};
Arrays.sort(indices, comparator);
System.out.println(Arrays.toString(indices));

输出:

[0, 2, 5, 1, 4, 3]
  • 您可以通过更改compare()方法中的比较顺序,将输出顺序从升序更改为降序:

    public int compare(Integer arg0, Integer arg1) {
        return values[arg1].compareTo(values[arg0]);
    }
    
  • 您还可以使用任何其他可比数据类型更改Long[]

相关问题