前言
之前总结了交换排序的一种——冒泡排序,今天来说另外一种——快速排序。
快速排序
何为快速排序,它实质上是对冒泡排序的一种改进,基本思想:在n个记录中取某一个记录的键值为标准,通常取第一个键值为基准,通过一趟排序将待排序的记录分为小于或等于这个键值和大于这个键值的两个独立的部分,这时一部分的记录键值均比另一部分记录的键值小,然后,对这两部分记录继续分别进行快速排序,以达到整个序列有序。
效果图
代码
类C描述
void QuickSort(List R,int low,int high)//总快速排序
{
if(low<high)
{
temp=QuickPartition(R,low,high);
QuickSort(R,low,temp-1);//分治思想
QuickSort(R,temp+1,high);
}
}
int QuickPartition(List R,int low,int high)//每次循环代码
{
x=R[low];
while(low<high)
{
while((low<high)&&(R[high].key>=x.key))
high--;
R[low]=R[high];
while((low<high)&&(R[low].key<=x.key))
low++;
R[high]=R[low];
}
R[low]=x;
return low;
}
C#描述
static void Main(string[] args)//主程序
{
int[] R = { 3, 7, 8, 5, 2, 1, 9, 5, 4 };
int low = 0;
int high = R.Length - 1;
QuickSort(R, low, high);
Console.WriteLine("排序后数组:");
for (int i = 0; i <= R.Length - 1; i++)
{
Console.Write(R[i] + ",");
}
Console.WriteLine();
Console.ReadKey();
}
private static void QuickSort(int[] R,int low,int high)//总快速排序
{
int temp;
if(low<high)
{
temp = QuickPartition(R, low, high);
QuickSort(R, low, temp - 1);
QuickSort(R, temp + 1, high);
}
}
private static int QuickPartition(int[] R, int low, int high)//单次快速排序方法
{
int x = R[low];
while(low<high)
{
while(low <high && R[high]>=x)
{ high--; }
R[low] = R[high];
while(low<high && R[low]<=x)
{low++;}
R[high] = R[low];
}
R[low] = x;
return low;
}
注:快速排序有两种,分别是递归快速排序和非递归快速排序,本篇博客只写了递归快速排序,通过对两种类型的代码比较,更能体现快速排序的分治思想。
就平均时间性能而言,快速排序方法最佳,但在最坏情况下,即对几乎已是排好序的输入序列,时间复杂度高达O(n^2),另外,对于较小的n值该算法效果不明显,对于较大的n值效果较好。
总结
各种排序对比图
另附:快速排序舞蹈视频