【发布时间】:2011-06-02 04:26:29
【问题描述】:
我正在练习编写排序算法作为一些面试准备的一部分,我想知道是否有人可以帮助我找出为什么这种快速排序不是很快?它似乎具有正确的运行时复杂性,但它比我的合并排序慢约 2 的常数因子。我也将感谢任何可以改进我的代码但不一定回答问题的 cmet。
非常感谢您的帮助!如果我犯了任何礼仪错误,请不要犹豫,让我知道。这是我在这里的第一个问题。
private class QuickSort implements Sort {
@Override
public int[] sortItems(int[] ts) {
List<Integer> toSort = new ArrayList<Integer>();
for (int i : ts) {
toSort.add(i);
}
toSort = partition(toSort);
int[] ret = new int[ts.length];
for (int i = 0; i < toSort.size(); i++) {
ret[i] = toSort.get(i);
}
return ret;
}
private List<Integer> partition(List<Integer> toSort) {
if (toSort.size() <= 1)
return toSort;
int pivotIndex = myRandom.nextInt(toSort.size());
Integer pivot = toSort.get(pivotIndex);
toSort.remove(pivotIndex);
List<Integer> left = new ArrayList<Integer>();
List<Integer> right = new ArrayList<Integer>();
for (int i : toSort) {
if (i > pivot)
right.add(i);
else
left.add(i);
}
left = partition(left);
right = partition(right);
left.add(pivot);
left.addAll(right);
return left;
}
}
非常感谢所有帮助过的人!
这是我为后代大大改进的课程:
private class QuickSort implements Sort {
@Override
public int[] sortItems(int[] ts) {
int[] ret = ts.clone();
partition(ret,0,ret.length);
return ret;
}
private void partition(int[] toSort,int start,int end) {
if(end-start<1) return;
int pivotIndex = start+myRandom.nextInt(end-start);
int pivot = toSort[pivotIndex];
int curSorted = start;
swap(toSort,pivotIndex,start);
for(int j = start+1; j < end; j++) {
if(toSort[j]<pivot) {
if(j!=curSorted+1)
swap(toSort,curSorted,curSorted+1);
swap(toSort,j,curSorted++);
}
}
// Now pivot is at curSorted
partition(toSort,start,curSorted);
partition(toSort,curSorted+1,end);
}
}
【问题讨论】:
-
只是把它扔在那里,但是当数组的数字完全随机时,快速排序实际上是最快的,而不是在这种情况下顺序无关紧要的合并排序。
-
我建议你看看集合中的快速排序代码。它相当快速和高效。或者你可以直接使用它。
-
标题讽刺+1 :)
标签: java sorting complexity-theory quicksort