【发布时间】:2025-12-31 19:20:07
【问题描述】:
我正在尝试为我自己的启迪编写一个快速排序。我使用pseudocode on wikipedia 作为指导。我的代码有效。它似乎应该在 O(n log n) 时间内运行。我尝试实际计时我的代码以检查复杂性(即,当我将输入大小加倍时,运行时间是否增加了大约 n log n),但我仍然不确定。
我的代码看起来很简单。我就地进行排序。我见过的其他实现使用了我没有的分区函数。这让我觉得我已经实现了一些其他的排序算法。这是快速排序算法吗?
public static void QuickSortInPlace(int[] arr)
{
QuickSortInPlace(arr, 0, arr.Length - 1);
}
private static void QuickSortInPlace(int[] arr, int left, int right)
{
if (left < right)
{
//move the middle int to the beginning and use it as the pivot
Swap(arr, left, (left + right) / 2);
int pivotIndex = left;
int pivot = arr[pivotIndex];
int min = left + 1;
int max = right;
for (int i = min; i <= max; i++)
{
if (arr[i] > pivot)
{
Swap(arr, i, max);
max--; //no longer need to inspect ints that have been swapped to the end
i--; //reset the loop counter to inspect the new int at the swapped position
}
}
//move pivot to its sorted position
Swap(arr, max, pivotIndex);
//recurse on the sub-arrays to the left and right of the pivot
QuickSortInPlace(arr, left, max - 1);
QuickSortInPlace(arr, max + 1, right);
}
}
基于 Dukeling 的回应的第二个版本。
public static void QuickSortInPlace3(int[] arr, int min, int max)
{
if (min < max)
{
int pivotIndex = min;
int pivot = arr[pivotIndex];
int left = min;
int right = max;
while (left <= right)
{
while (arr[left] < pivot)
left++;
while (arr[right] > pivot)
right--;
if (left <= right)
{
Swap(arr, left, right);
left++;
right--;
}
}
QuickSortInPlace3(arr, min, right);
QuickSortInPlace3(arr, left, max);
}
}
【问题讨论】:
标签: c# algorithm quicksort in-place