#include <stdio.h>
#include <stdlib.h>
#include<assert.h>
#include<time.h>
//count用来记录次数
int count1 = 0;
int count2 = 0;
void Show(int *arr,int len)
{
for (int i = 0; i < len; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}
//找到当前区间基准位置,左边的值比该值小,右边的比该值大,左右两边都要找一遍; 可以用来找topk
int Parition(int *arr, int low,int high)
{
int tmp = arr[low];//拿出单独的一个基准
while (low < high)
{
while (arr[high] >= tmp && low <high)//添加等于可进行相同数字的处理
{
count1++;
high--;
}
arr[low]=arr[high];
while (arr[low] <= tmp && low < high)
{
count1++;
low++;
}
arr[high]=arr[low];//low == high或者arr[low]>tmp才执行这句
}
arr[low] = tmp;
return low;
}
void Quick(int *arr, int low, int high)
{
if (low < high)
{
int part = Parition(arr, low, high);
Quick(arr, low, part - 1);
Quick(arr, part + 1, high);
}
}
//快速排序 找到中间分割点,再递归
void QuickSort(int *arr,int len)
{
if (arr == NULL)return;
Quick(arr,0,len-1);
}
//快速排序非递归
void Sort_Quick(int *arr, int len)
{
if (arr == NULL) return;
int *stack = (int *)malloc(sizeof(int)*len);
assert(stack != NULL);
int low = 0;
int top = 0;
int high = 0;
int Part = 0;
stack[top++] = 0;
stack[top++] = len - 1;
while (top != 0)//栈不为空
{
high=stack[--top];
low = stack[--top];
Part = Parition(arr,low,high);//反复利用该函数排序找一下中间值
if (low < Part-1)//左边入栈
{
count2++;
stack[top++]=low;
stack[top++]=Part-1;
}
if (Part+1 < high)//右边入栈
{
count2++;
stack[top++] = Part+1;
stack[top++] = high;
}
}
free(stack);//释放申请的额外空间
}
int main()
{
int arr1[] = {11,3,15,10,7,2,44,1,0};
int n1 = sizeof(arr1) / sizeof(sizeof(arr1[0]));
printf("快速排序(递归):\n");
QuickSort(arr1,n1);
Show(arr1, n1);
printf("执行次数:%d\n",count1);
int arr2[] = { 11, 3, 15, 10, 7, 2, 44, 1, 0 };
int n2 = sizeof(arr2) / sizeof(sizeof(arr2[0]));
printf("快速排序(非递归):\n");
Sort_Quick(arr2, n2);
Show(arr2, n2);
printf("执行次数:%d\n", count2);
return 0;
}
运行结果:
快速排序的时间复杂度:
最坏情况是每次划分选取的基准都是当前无序区中关键字最小(或最大)的记录,划分的结果是基准左边的子区间为空(或右边的子区间为空),而划分所得的另一个非空的子区间中记录数目,仅仅比划分前的无序区中记录个数减少一个。时间复杂度为O(n*n)
最好情况是每次划分所取的基准都是当前无序区的"中值"记录,划分的结果是基准的左、右两个无序子区间的长度大致相等。总的关键字比较次数:O(nlgn)
尽管快速排序的最坏时间为O(n2),但就平均性能而言,它是基于关键字比较的内部排序算法中速度最快者。它的平均时间复杂度为O(nlgn)。