[英]Quick Sort on C# using only while loop
我一直在尝试以一种特定的方式实现快速排序,但我无法在整个 inte.net 上找到它-
问题是我的算法有错误,我无法弄清楚。 谁能告诉我我做错了什么?
这是我的代码:
public static void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int partition(int[] a, int start, int end)
{
int pivot = a[end];
int i = start;
int j = end - 1;
while (i < j)
{
while (i < j && a[i] <= pivot)
i++;
while (i < j && a[j] > pivot)
j--;
swap(a, i, j);
}
swap(a, i+1, end);
return i+1 ;
}
public static void QuickSort(int[] a, int start, int end)
{
if (start >= end)
return;
int p = partition(a, start, end);
QuickSort(a, start, p - 1);
QuickSort(a, p + 1, end);
}
static void Main(string[] args)
{
int[] a = { 9, 1, 4, 7, 3 };
QuickSort(a, 0, a.Length-1);
//PrintArr(a);
}
你的分区方法有问题。
你应该这样。
public static int partition(int[] a, int start, int end)
{
int pivot = a[end];
int i = (start - 1);
for (int j = start; j <= end - 1; j++)
{
if (a[j] < pivot)
{
i++;
swap(a, i, j);
}
}
swap(a, i + 1, end);
return (i + 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.