Java Array sort:获取数组索引排序列表的快速方法 [英] Java Array sort: Quick way to get a sorted list of indices of an array
问题描述
问题:考虑以下浮点数[]:
The problem: Consider the following floats[]:
d[i] = 1.7 -0.3 2.1 0.5
我想要的是一个 int[] 数组,它用索引表示原始数组的顺序.
What I want is an array of int[] that represents the order of the original array with indices.
s[i] = 1 3 0 2
d[s[i]] = -0.3 0.5 1.7 2.1
当然可以使用自定义比较器、一组排序的自定义对象或通过简单地对数组进行排序然后在原始数组中搜索索引来完成(不寒而栗).
Of course it could be done with a custom comparator, a sorted set of custom objects, or by simply sorting the array and then searching for the indices in the original array (shudder).
我实际上正在寻找的是 Matlab 的排序函数.
What I am in fact looking for is the equivalent for the second return argument of Matlab's sort function.
有没有一种简单的方法可以做到这一点(<5 LOC)?有没有一种不需要为每个元素分配一个新对象的解决方案?
Is there an easy way to do that (<5 LOC)? May there be a solution that does not need to allocate a new object for each element?
更新:
感谢您的回复.不幸的是,到目前为止所提出的方案都不像我所希望的简单有效的解决方案.因此,我在 JDK 反馈论坛中开了一个帖子,提议添加一个新的类库函数来解决这个问题.让我们看看 Sun/Oracle 是如何看待这个问题的.
Thanks for your responses. Unfortunately, none of what has been proposed so far resembles the simple and efficient solution I was hoping for. I therefore openened a thread in the JDK feedback forum, proposing the addition of a new class-library function to address the issue. Lets see what Sun/Oracle thinks about the issue.
http://forums.java.net/jive/thread.jspa?threadID=62657&tstart=0
推荐答案
我会调整快速排序算法来同时对多个数组执行交换操作:索引数组和值数组.例如(基于此 quicksort):
I would tailor the quicksort algorithm to perform the exchange operation on multiple arrays at the same time: the index array and the value array. For example (based on this quicksort):
public static void quicksort(float[] main, int[] index) {
quicksort(main, index, 0, index.length - 1);
}
// quicksort a[left] to a[right]
public static void quicksort(float[] a, int[] index, int left, int right) {
if (right <= left) return;
int i = partition(a, index, left, right);
quicksort(a, index, left, i-1);
quicksort(a, index, i+1, right);
}
// partition a[left] to a[right], assumes left < right
private static int partition(float[] a, int[] index,
int left, int right) {
int i = left - 1;
int j = right;
while (true) {
while (less(a[++i], a[right])) // find item on left to swap
; // a[right] acts as sentinel
while (less(a[right], a[--j])) // find item on right to swap
if (j == left) break; // don't go out-of-bounds
if (i >= j) break; // check if pointers cross
exch(a, index, i, j); // swap two elements into place
}
exch(a, index, i, right); // swap with partition element
return i;
}
// is x < y ?
private static boolean less(float x, float y) {
return (x < y);
}
// exchange a[i] and a[j]
private static void exch(float[] a, int[] index, int i, int j) {
float swap = a[i];
a[i] = a[j];
a[j] = swap;
int b = index[i];
index[i] = index[j];
index[j] = b;
}
这篇关于Java Array sort:获取数组索引排序列表的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!