[C#] 纯文本查看 复制代码 /// <summary>
/// Quick Sort
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array"></param>
public static void QuickSort<T>(T[] array,int left,int right) where T : IComparable
{
if (left < right)
{
int middle = GetMiddleFroQuickSort<T>(array, left, right);
QuickSort<T>(array, left, middle - 1);
QuickSort<T>(array, middle + 1, right);
}
}
/// <summary>
/// get the index of the middle value for qucik sort
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array"></param>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
private static int GetMiddleFroQuickSort<T>(T[] array, int left, int right) where T : IComparable
{
T key = array[left];
while (left < right)
{
while (left < right && key.CompareTo(array[right]) < 0)
{
right--;
}
if (left < right)
{
T temp = array[left];
array[left] = array[right];
//Console.WriteLine("array[{0}]:{1} ----> arry[{2}]:{3}", left, temp, right, array[right]);
left++;
}
while (left < right && key.CompareTo(array[left]) > 0)
{
left++;
}
if (left < right)
{
T temp = array[right];
array[right] = array[left];
//Console.WriteLine("array[{0}]:{1} ----> arry[{2}]:{3}", right, temp, left, array[left]);
right--;
}
array[left] = key;
}
//Console.WriteLine("find the middle value {0} and the index {1}", array[left], left);
return left;
}
|