快速排序(分治法)

问题描述参考:http://blog.csdn.net/code_ac/article/details/74158681

算法实现部分:

//random_quick_sort.cpp
#include "random_quick_sort.h"
#include <stdlib.h>

template<class Type>
void RandomQuickSort(Type a[], int p, int r)
{
    if (p < r)
    {
        int q = random_partition(a, p, r);
        RandomQuickSort(a, p, q - 1);
        RandomQuickSort(a, q + 1, r);
    }
}
//随机产生基准数
template <class Type>
int random_partition(Type a[], int p, int r)
{
    int i = rand() % (r - p) + p;
    Type b;
    b = a[p];
    a[p] = a[i];
    a[i] = b;
    return partition(a, p, r);
}

//根据基准元素进行排序
template <class Type>
int partition(Type a[], int p, int r)
{
    int i = p, j = r + 1;
    Type b;
    Type x = a[p];  //以a[p]作为基准元素
    while (true)
    {
        while (a[++i] < x && i < r);
        while (a[--j] > x);
        if (i >= j)
            break;
        b = a[j];
        a[j] = a[i];
        a[i] = b;
    }
    a[p] = a[j];
    a[j] = x;
    return j;
}

 

头文件:

//random_quick_sort.h
#ifndef RANDOM_QUICK_SORT_H
#define RANDOM_QUICK_SORT_H

template <class Type>
void RandomQuickSort(Type a[], int p, int r);


#endif

 

主函数:

//main.cpp
#include<iostream>
#include "random_quick_sort.cpp"

using namespace std;

#define Type int  //定义数组元素类型

int main()
{
    int size;  //数组大小
    cout << "请输入数组大小: ";
    cin >> size;
    Type *a = new Type[size];  //定义一个数组
    cout << "请输入数组元素:  " << endl;
    for (int i = 0; i < size; i++)
    {
        cin >> a[i];
    }
    RandomQuickSort(a, 0, size - 1);
    cout << "输出快速排序后的数组:" << endl;
    for (int j = 0; j < size; j++)
    {
        cout << a[j] << "   ";
    }
    system("pause");
    delete a;
    return 0;
}

 注意:这里的基准数是随机产生的,从而期望划分是较为对称的;

转载于:https://www.cnblogs.com/zf-blog/p/8370741.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值