QuickSort之C#实现
/// <summary>
/// 快速排序中的切分
/// lIndex已经是基准值,i记录基准值的大小值的边界,j记录目前遍历的边界;
/// i值必须从lIndex+1开始,因为基准值已经在lIndex位置了,
/// i位置的值必须大于基准值,因为发现比基准值小的值,需要和i位置的值交换,
/// 交换结束后,i++,变更基准边界值;
/// 最后,交换基准值和i-1位置的值,基准值归位,i-1位置是基准值的大小值边界,
/// 返回i-1
/// </summary>
/// <param name="values"></param>
/// <param name="lIndex"></param>
/// <param name="rIndex"></param>
/// <returns></returns>
public static int Partition(int[] values,int lIndex,int rIndex)
{
int p = values[lIndex];
int i = lIndex+1;
for(int j = lIndex + 1; j <= rIndex; j++)
{
if (values[j] < p)
{
int temp = values[i];
values[i] = values[j];
values[j] = temp;
i++;
}
}
int tempp = values[lIndex];
values[lIndex] = values[i - 1];
values[i - 1] = tempp;
return i - 1;
}
public static void QuickSort(int[] values,int lIndex,int rIndex)
{
if (lIndex >= rIndex)
{
return;
}
int index = ChoosePivot(values, lIndex, rIndex);
int temp = values[index];
values[index] = values[lIndex];
values[lIndex] = temp;
int j = Partition(values, lIndex, rIndex);
QuickSort(values, lIndex, j - 1);
QuickSort(values, j + 1, rIndex);
}
public static int ChoosePivot(int[] values,int lIndex,int rIndex)
{
Random rand = new Random();
int index = rand.Next(lIndex, rIndex);
return lIndex;
}
int[] values = new int[100000];
Random rand = new Random();
for(int i = 0; i < values.Length; i++)
{
values[i] = rand.Next(0, values.Length);
}
int[] valuesCopy = (int[])values.Clone();
bool ifEqual = true;
for(int i = 0; i < values.Length; i++)
{
if(values[i] != valuesCopy[i])
{
ifEqual = false;
}
}
Console.WriteLine($"排序前:ifEqual->{ifEqual}");
Stopwatch sw = new Stopwatch();
sw.Start();
AlgorithmMethod.QuickSort(values, 0, values.Length - 1);
sw.Stop();
Console.WriteLine($"QuickSort用时:{sw.ElapsedMilliseconds}ms");
sw.Restart();
var a = valuesCopy.ToList();
a.Sort();
valuesCopy = a.ToArray();
sw.Stop();
Console.WriteLine($"Order用时:{sw.ElapsedMilliseconds}ms");
ifEqual = true;
for (int i = 0; i < values.Length; i++)
{
if (values[i] != valuesCopy[i])
{
ifEqual = false;
}
}
Console.WriteLine($"排序后:ifEqual->{ifEqual}");
排序前:ifEqual->True
QuickSort用时:46ms
Order用时:5ms
排序后:ifEqual->True
#####
愿你一寸一寸地攻城略地,一点一点地焕然一新
#####