我正在将书籍介绍中的 QuickSort 算法应用到我编写代码的算法中,但输出未正确排序
以下是算法
Quicksort(A, p, r)
{
if (p < r)
{
q = Partition(A, p, r)
Quicksort(A, p, q-1)
Quicksort(A, q+1, r)
}
}
Partition(A, p, r)
{
pivot = A[r]
i = p - 1
for j = p to r – 1
{
do if A[j] <= pivot
then
{
i = i + 1
exchange A[i] A[j]
}
}
exchange A[i+1] A[r]
return i+1
}
这是我的代码
class Threads<T>
{
static bool IsLessThan(T x, T y)
{
if (((IComparable)(x)).CompareTo(y)<=0)
{
return true;
}
else {
return false;
}
}
public int Partition(T[] myarray, int low, int high)
{
T x = myarray[high];
T y;
int i = low - 1;
int j;
for (j = low; j < high - 1; j++)
{
//**************Added Text after edit,I forgot to put this
if (IsLessThan(myarray[j], x))
{
i++;
y = myarray[i];
myarray[i] = myarray[j];
myarray[j] = y;
}
}
y = myarray[i+1];
myarray[i+1] = myarray[high];
myarray[high] = y;
return i + 1;
}
public void QuickSort(T[] myarray, int low, int high)
{
if (low < high)
{
// int q = Partition(myarray,highh, low);
int q = Partition(myarray,low, high);
QuickSort(myarray, low, q - 1);
QuickSort(myarray, q + 1, high );
}
}
}
以下代码显示了如何使用快速排序方法
private void button1_Click(object sender, EventArgs e)
{
int[] myarray ={9,8,7,6,5,4,3,2};
textBox1.Text = "";
Threads<int> t1 = new Threads<int>();
t1.QuickSort(myarray, 0, myarray.Length-1);
for(int i=0;i<myarray.Length;i++)
textBox1.Text=textBox1.Text+" , "+myarray[i];
}
执行程序时得到以下输出
8 , 7 , 6 , 5 , 4 , 3 , 9 , 2
回答
i 的值必须比 j 小 1 并且在 Partition 函数开始时为低
我忘记在分区函数的循环之外交换 myarray[i+1] 和 myarray[high]。
现在代码对于字符串、int、char 等都可以正常工作