快速排序

#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)。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值