由于这里也没有“快速”的答案,我继续自己实现了这样的分类设备。
public class IntListUtils {
public interface IntIntComparator {
int compare(int a, int b);
}
public static void sort(MutableIntList subject, IntIntComparator comparator) {
quicksort(subject, 0, subject.size() - 1, comparator);
}
public static void quicksort(MutableIntList subject, int low, int high, IntIntComparator comparator) {
if (low >= high) { return; }
int pivot = partition(subject, low, high, comparator);
quicksort(subject, low, pivot - 1, comparator);
quicksort(subject, pivot, high, comparator);
}
private static int partition(MutableIntList subject, int low, int high, IntIntComparator comparator) {
int pivot = subject.get(high);
int i = low;
for (int j = low; j <= high - 1; j++) {
if (comparator.compare(subject.get(j), pivot) < 0) {
int t = subject.get(i);
subject.set(i, subject.get(j));
subject.set(j, t);
i += 1;
}
}
int t = subject.get(i);
subject.set(i, subject.get(high));
subject.set(high, t);
return i;
}
}
可以使用它来实现我上面描述的排序顺序:
MutableIntList list = ...;
IntListUtils.sort(list, (a, b) -> {
// negative before non-negative
// otherwise, smallest numbers first
if (a == b) { return 0; }
if (a < 0 && b < 0) {
return (a < b) ? 1 : -1;
}
return (a < b) ? -1 : 1;
});
编辑:我意识到这种快速排序并不是目前最快的排序方法,但它所要做的就是比排序后将我的整个IntList
转换为 aList<Integer>
并返回更快,这在排序时分配 O(n) 内存(n 很大)方法就地发生。