快速排序

/*
 *快排的基本思想:
 *     现在源数据中任意去一个值,作为标准值。把
 * 数据中小于标准值的数据排在该标准值的左边,把
 * 数据中大于等于标准值的数据排在该标准值的右边。
 * 这样就分成了三部分。
 *    左半边   标准值   右半边
 *然后分别在左半边和右半边进行取标准值,划分左半
 *边和右半边。
 *   
 *可用到递归思想或栈的数据结构
*/

#include <iostream>
#include <iomanip>
using namespace std;

#define Size 20
typedef int DataType;
void QuickSort(DataType digit[], int low, int high);
void PaintQuickSort(DataType digit[], int lengthOfDigit);
int main(void)
{
    DataType digit[Size] ={
		12, 45, 56, 56, 98,
		23, 44, 22, 49, 78,
		34, 26, 65, 84, 73,
		28, 45, 84, 74, 88};
	PaintQuickSort(digit, Size);
	QuickSort(digit, 0, Size-1);
	PaintQuickSort(digit, Size);
	return 0;
}
//快速排序
void QuickSort(DataType digit[], int low, int high)
{
	int i = low;
	int j = high;
	DataType  temp = digit[low]; // 选取标准值
    while(i < j)//结束条件是 high <= low
	{
		while(i < j && temp < digit[j]) j--; // 在数组的右边扫描
		if(i < j)
		{
			digit[i] = digit[j];
			i++;
		}
		while(i < j && temp > digit[i]) i++; // 在数组的左边扫描
		if(i < j)
		{
			digit[j] = digit[i];
			j--;
		}
	}
	digit[i] = temp;
	if( low < i) QuickSort(digit,low, i-1); //递归
	if( i < high) QuickSort(digit, i+1, high);//递归
	cout<<"After QuickSort..."<<endl;//帮助你理解递归
}
///输出
void PaintQuickSort(DataType digit[], int lengthOfDigit)
{
	for(int i = 0; i < lengthOfDigit; i++)
	{
		cout<<digit[i]<<setw(3);
	}
	cout<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值