快速排序算法[C/C++]

快速排序算法

笔记:

#include<iostream>
#include<string.h>
using namespace std;
void quite_sort(int *a,int low,int high);
int partitions(int *a,int low, int high);
int main()
{
	int a[201];
	int n;
	memset(a,0,sizeof(a));
	cin >> n;
	int i;
	for(i = 0;i < n; i++)
	{
		cin >> a[i];
	}
	quite_sort(a,0,n - 1);

		for(i = 0;i < n; i++)
		{
			cout << a[i]  << " ";
		}
}

int partitions(int *a,int low, int high)
{
	int p = a[low];
	 
	while(low < high)
	{
		while(a[high] >= p && low < high)//注意这里的a[high] >= p和下面的a[low] < p一定要形成闭区间,就是一个有等号一个没有等号 
		{								 //为什么外面已经有一个while low < high了里面还要写一个,能不能省略?不能,因为里面的i和j双向在变化,可能满足外部条件但是到了循环内部变化一次就不循环了,此时low,high就不应该再做运算了 
			high --;
		}
		
		if(low >= high)
		{
			break;
		}
		else
			a[low] = a[high];//一定要先吧a[low]覆盖,因为a[low]的值已经存储了 
		while(a[low] < p && low < high)
		{
			low ++; 
		}
		
		if(low >= high)
		{
			break;
		}
		else
			a[high] = a[low];
			
	}
	a[low] = p;
	return low;
 } 

void quite_sort(int *a,int low,int high)
{
	if(low < high)//快排永恒的条件,递归就不用循环了,所以这里是if不是while  
	{
		int p = partitions(a,low,high);
		quite_sort(a,low,p - 1);
		quite_sort(a,p + 1,high);
	}

	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值