【发布时间】:2018-02-16 08:07:13
【问题描述】:
我正在尝试实现经典 CLRS 书中给出的快速排序算法。我已经在我的 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 伪代码中是否存在错误(极不可能)?
请帮忙!
【问题讨论】:
-
盯着输出,你能发现输出的共同点吗?在 Lomuto 分区的 stab 中进行比较时使用了哪些索引?
-
@greybeard - 感谢您的快速回复。我一直在尝试调试它,但由于它是一个 exact 伪代码实现,它不应该“开箱即用”吗?