数据结构——快速排序

快速排序

codeblocks 17 通过

Code

// @ChenYe 2018/12/05
#include <iostream>
#define MAXSIZE 1000

using namespace std;
int len;    // 全局长度变量ing namespace std;
int Count = 0;  // 计数

void Swap(int a[], int low, int high)
{
	int temp;

	temp = a[low];
	a[low] = a[high];
	a[high] = temp;
}

int Partition(int a[], int low, int high)
{// 计算基准点,并将小于基准点的元素放在基准点左边,大于的放右边
	int point;

	point = a[low];

	while( low < high )
	{// while循环一遍a数组,以piont为基准值分成两边
		while( low < high && a[high] >= point )// 比较右边
		{
			high--;Count++;
		}// 出whille的时候说明需要移动了
		Swap(a, low, high);

		while( low < high && a[low] <= point )// 比较左边
		{
			low++;Count++;
		}// 出whille的时候说明需要移动了
		Swap(a, low, high);
	}

	return low;
}

void QSort(int k[], int low, int high)
{// 出递归条件low == high
	int point;

	if( low < high )
	{
		point = Partition(k, low, high);    // 计算基准点的函数(关键)

        // 递归基准点左右
		QSort(k, low, point-1);
		QSort(k, point+1, high);
	}
}

void QuickSort(int a[])
{
    QSort(a, 0, len-1);
}

int main()
{
    int num[MAXSIZE];
    int n,i, key;
    // 输入
    for(n=0; n<MAXSIZE; n++)    // 从下表0开始
    {
        cin>>key;
        if(key==0)
            break;
        num[n] = key;
    }
    len = n;

    // 快速排序
    QuickSort(num);

    // output
    for(i=0; i<n; i++)
    {
        cout<<num[i]<<" ";
    }
    cout<<"\nsum up to"<<Count<<endl;
    return 0;
}
/*
test data:
输入:
1 9 8 5 7 6 4 3 2 0
输出:
1 2 3 4 5 6 7 8 9


*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值