就(渐进)时间复杂度而言,它们是相同的。
"递归比迭代慢" - 这种说法的原因是由于递归栈的开销(在调用之间保存和恢复环境)。
然而,这些是常数次操作,不会改变“迭代”的次数。
无论是递归还是迭代快速排序都是O(nlogn)
平均情况和O(n^2)
最坏情况。
编辑:
仅仅为了好玩,我运行了附在帖子中的(java)代码的基准测试,然后我进行了Wilcoxon统计检验,以检查运行时间是否确实不同。
结果可能是有决定性的(P_VALUE=2.6e-34,https://en.wikipedia.org/wiki/P-value。请记住,P_VALUE是P(T >= t | H),其中T是测试统计量,H是零假设)。但答案并不是你期望的。
迭代解法的平均值为408.86毫秒,而递归解法的平均值为236.81毫秒。
(注意 - 我使用Integer
而不是int
作为recursiveQsort()
的参数 - 否则递归会表现得更好,因为它不必装箱很多整数,这也很耗时 - 我这样做是因为迭代解法别无选择。)
因此,你的假设是不正确的,在我的机器和Java环境下,递归解决方案比P_VALUE = 2.6e-34的迭代解决方案更快。
public static void recursiveQsort(int[] arr,Integer start, Integer end) {
if (end - start < 2) return;
int p = start + ((end-start)/2);
p = partition(arr,p,start,end);
recursiveQsort(arr, start, p);
recursiveQsort(arr, p+1, end);
}
public static void iterativeQsort(int[] arr) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
stack.push(arr.length);
while (!stack.isEmpty()) {
int end = stack.pop();
int start = stack.pop();
if (end - start < 2) continue;
int p = start + ((end-start)/2);
p = partition(arr,p,start,end);
stack.push(p+1);
stack.push(end);
stack.push(start);
stack.push(p);
}
}
private static int partition(int[] arr, int p, int start, int end) {
int l = start;
int h = end - 2;
int piv = arr[p];
swap(arr,p,end-1);
while (l < h) {
if (arr[l] < piv) {
l++;
} else if (arr[h] >= piv) {
h--;
} else {
swap(arr,l,h);
}
}
int idx = h;
if (arr[h] < piv) idx++;
swap(arr,end-1,idx);
return idx;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String... args) throws Exception {
Random r = new Random(1);
int SIZE = 1000000;
int N = 100;
int[] arr = new int[SIZE];
int[] millisRecursive = new int[N];
int[] millisIterative = new int[N];
for (int t = 0; t < N; t++) {
for (int i = 0; i < SIZE; i++) {
arr[i] = r.nextInt(SIZE);
}
int[] tempArr = Arrays.copyOf(arr, arr.length);
long start = System.currentTimeMillis();
iterativeQsort(tempArr);
millisIterative[t] = (int)(System.currentTimeMillis()-start);
tempArr = Arrays.copyOf(arr, arr.length);
start = System.currentTimeMillis();
recursvieQsort(tempArr,0,arr.length);
millisRecursive[t] = (int)(System.currentTimeMillis()-start);
}
int sum = 0;
for (int x : millisRecursive) {
System.out.println(x);
sum += x;
}
System.out.println("end of recursive. AVG = " + ((double)sum)/millisRecursive.length);
sum = 0;
for (int x : millisIterative) {
System.out.println(x);
sum += x;
}
System.out.println("end of iterative. AVG = " + ((double)sum)/millisIterative.length);
}