快速排序 C语言实现

快速排序(假设我们要排成升序)的思想是:

取第一个值为中间值,然后遍历(虽然是从数组两边同时遍历,但是时间复杂度依旧是O(n)),把比中间值小的放在中间值左边,把比中间值大的放在中间值右边。

然后两边继续刚才的循环,其实也就是递归。

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

void sort_(int *,int,int);//排序 

int findpos(int*,int,int);//找到第一个元素排序后(其实还没排),应该所在的位置 

int main(void)
{
	int i;
	int a[5] = {5,4,3,2,-1};
	sort_(a,0,4);//将下表0~4的元素进行排列 
	for(i=0;i<5;i++)
	{
		printf("%d ",a[i]);
	}
	return 0;
} 
void sort_(int *p,int low,int high)
{
	if(low<high)
	{
		int pos = findpos(p,low,high);
		sort_(p,low,pos-1);//对中间值两边的数组继续进行刚刚的操作 
		sort_(p,pos+1,high);
	}
}

int findpos(int*p,int low,int high)
{
	int val = p[low];
	while(low<high)
	{
		while(low<high && val<= p[high])
			{
				high--;
			}
		p[low] = p[high];
		while(low<high && val>= p[low])
			{
				low++;
			 } 
		p[high] = p[low];
	}
	p[low] = val;
	return low;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值