Tik*_*iki 2 java sorting complexity-theory quicksort
我正在练习编写排序算法作为一些面试准备的一部分,我想知道是否有人可以帮助我发现为什么这种快速排序不是很快?它似乎具有正确的运行时复杂性,但它比我的合并排序慢了大约2的常数因子.我也很感激任何可以改进我的代码的注释,但不一定能回答这个问题.
非常感谢你的帮助!如果我犯了礼仪错误,请不要犹豫,告诉我.这是我的第一个问题.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢,所有帮助过的人!
这是我为子孙后代改进的课程:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Quicksort最大的优势之一是它可以作为就地算法实现.不要创建新列表,而是在原地对元素进行排序.
| 归档时间: |
|
| 查看次数: |
1620 次 |
| 最近记录: |