我正在尝试实现经典CLRS书中给出的Quicksort算法。我已经在我的C#程序中逐行实现了 。但输出未分类。以下是我的代码,以及输出:
using System;
namespace clrs
{
class MainClass
{
public static void Main (string[] args)
{
int[] numbers = { 2, 1, 4 };
Console.WriteLine("unsorted: " + string.Join(",", numbers));
quicksort (numbers, 0, numbers.Length-1);
Console.WriteLine("sorted: " + string.Join(",", numbers));
Console.WriteLine("");
numbers = new int[]{ 7, 2, 1, 6, 1 };
Console.WriteLine("unsorted: " + string.Join(",", numbers));
quicksort (numbers, 0, numbers.Length-1);
Console.WriteLine("sorted: " + string.Join(",", numbers));
Console.WriteLine("");
numbers = new int[]{ 2,8,7,1,3,5,6,4 };
Console.WriteLine("unsorted: " + string.Join(",", numbers));
quicksort (numbers, 0, numbers.Length-1);
Console.WriteLine("sorted: " + string.Join(",", numbers));
Console.WriteLine("");
numbers = new int[]{ 2, 33, 6, 9, 8, 7, 1, 2, 5, 4, 7 };
Console.WriteLine("unsorted: " + string.Join(",", numbers));
quicksort (numbers, 0, numbers.Length-1);
Console.WriteLine("sorted: " + string.Join(",", numbers));
Console.WriteLine("");
}
public static void quicksort(int[] a, int p, int r){
int q;
if (p < r){
q = partition (a, p, r);
quicksort(a, p, q-1);
quicksort(a, q+1, r);
}
}
public static int partition(int[] a, int p, int r){
int x = a[r];
int i = p - 1;
for (int j=p; j<r-1; j++){
if(a[j] <= x){
i = i + 1;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
int temp1 = a[i+1];
a[i+1] = a[r];
a[r] = temp1;
return (i+1);
}
}
}
输出结果为:
unsorted: 2,1,4
sorted: 2,4,1
unsorted: 7,2,1,6,1
sorted: 1,1,2,7,6
unsorted: 2,8,7,1,3,5,6,4
sorted: 2,3,1,4,5,7,8,6
unsorted: 2,33,6,9,8,7,1,2,5,4,7
sorted: 1,2,5,6,7,2,7,8,9,33,4
我已经实现了快速排序完全,因为它是在CLRS第3版中给出的。我的代码编译但输出没有完全排序。
我做错了什么?或者CLRS伪代码中是否存在错误(极不可能)?
请帮助!
答案 0 :(得分:2)
我打电话给恶作剧......似乎有人打错了
此
for (int j=p; j<r-1; j++){
应该是这个
for (int j=p; j<r; j++){
在此测试
https://dotnetfiddle.net/XgIOpx
供参考
这是来自wiki的 Lomuto分区算法
algorithm quicksort(A, lo, hi) is
if lo < hi then
p := partition(A, lo, hi)
quicksort(A, lo, p - 1 )
quicksort(A, p + 1, hi)
algorithm partition(A, lo, hi) is
pivot := A[hi]
i := lo - 1
for j := lo to hi - 1 do
if A[j] < pivot then
i := i + 1
swap A[i] with A[j]
swap A[i + 1] with A[hi]
return i + 1
但是你需要特别注意
for j := lo to hi - 1 do // note the - 1
if A[j] < pivot then // and <
它必须是 - 1 或&lt; = ,而不是两者