代码拉取完成,页面将自动刷新
using System.Collections.Generic;
using Algorithms.Common;
namespace Algorithms.Sorting
{
public static class QuickSorter
{
//
// The public APIs for the quick sort algorithm.
public static void QuickSort<T>(this IList<T> collection, Comparer<T> comparer = null)
{
int startIndex = 0;
int endIndex = collection.Count - 1;
//
// If the comparer is Null, then initialize it using a default typed comparer
comparer = comparer ?? Comparer<T>.Default;
collection.InternalQuickSort(startIndex, endIndex, comparer);
}
//
// Private static method
// The recursive quick sort algorithm
private static void InternalQuickSort<T>(this IList<T> collection, int leftmostIndex, int rightmostIndex, Comparer<T> comparer)
{
//
// Recursive call check
if (leftmostIndex < rightmostIndex)
{
int wallIndex = collection.InternalPartition(leftmostIndex, rightmostIndex, comparer);
collection.InternalQuickSort(leftmostIndex, wallIndex - 1, comparer);
collection.InternalQuickSort(wallIndex + 1, rightmostIndex, comparer);
}
}
//
// Private static method
// The partition function, used in the quick sort algorithm
private static int InternalPartition<T>(this IList<T> collection, int leftmostIndex, int rightmostIndex, Comparer<T> comparer)
{
int wallIndex, pivotIndex;
// Choose the pivot
pivotIndex = rightmostIndex;
T pivotValue = collection[pivotIndex];
// Compare remaining array elements against pivotValue
wallIndex = leftmostIndex;
// Loop until pivot: exclusive!
for (int i = leftmostIndex; i <= (rightmostIndex - 1); i++)
{
// check if collection[i] <= pivotValue
if (comparer.Compare(collection[i], pivotValue) <= 0)
{
collection.Swap(i, wallIndex);
wallIndex++;
}
}
collection.Swap(wallIndex, pivotIndex);
return wallIndex;
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。