您的位置:首页 > 其它

快速排序(分治法)

2018-01-28 11:14 281 查看
问题描述参考: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;
}


注意:这里的[b]基准数是随机产生[/b]的,从而期望划分是较为对称的;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: