当前位置:文档之家› 分治算法实验(用分治法实现快速排序算法)

分治算法实验(用分治法实现快速排序算法)

算法分析与设计实验报告第四次附加实验
while (a[--j]>x); if (i>=j)
{
break;
}
Swap(a[i],a[j]);
}
a[p] = a[j]; //将基准元素放在合适的位置
a[j] = x;
return j;
}
//通过RandomizedPartition函数来产生随机的划分 template vclass
Type>
int RandomizedPartition(Type a[], int p, int r) {
int i = Random(p,r);
Swap(a[i],a[p]);
return Partition(a,p,r);
}
较小个数排序序列的结果:
测试结果
较大个数排序序列的结果:
实验心得
快速排序在之前的数据结构中也是学过的,在几大排序算法中,快速排序和归并排序尤其是
重中之重,之前的快速排序都是给定确定的轴值,所以存在一些极端的情况使得时间复杂度
很高,排序的效果并不是很好,现在学习的一种利用随机化的快速排序算法,通过随机的确
定轴值,从而可以期望划分是较对称
的,减少了出现极端情况的次数,使得排序的效率挺高了很多,
化算法想呼应,而且关键的是对于随机生成函数,通过这一次的
学习终于弄明白是怎么回事了,不错。

与后面的随机实
验和自己的
实验得分助教签名
附录:
完整代码(分治法)
//随机后标记元素后的快速排序
#i nclude <iostream>
#in elude <ctime>
#inelude <time.h> #include <iomanip> using namespacestd;
template < class Type>
void S &x,Type &y); // 声明swap函数
inline int Random(int x, int y); // 声明内联函数
template < class Type>
int Partition(Type a[], int p, int r); // 声明 Partition 函数template <class Type>
int RandomizedPartition(Type a[], int p, int r); // 声明 RandomizedPartition 函数
int a[1000000]; //定义全局变量用来存放要查找的数组
更大个数排序序列的结果:
template < class Type>
void RandomizedQuickSort(Type a[], int p, int r); // 声明 RandomizedQuickSort 函数
void ran( int *input, int n) // 随机生成数组元素函数{
int i;
srand(time(0));
for (i=0;i<n;i++) input[i]=rand()%100; // 生成的数据在0~100之间input[i]= '\0' ;
}
int main()
{
int n;
cout<< "请输入要排序的序列个数: " <<endl; cin>>n; // 输入要排序的序列个数 ran(a,n); // 随机生成数组 a
for (int i=0; i<n; i++) // 先将要排序的数组输出 {
cout<<a[i]<< " " ;
}
cout<<endl;
cout<<endl;
clock_t start,end,over; // 计算程序运行时间的算法
start=clock();
end=clock(); over=end-start;
start=clock();
// 调用随机化的快速排序 RandomizedQuickSort 函数
RandomizedQuickSort(a,0,n-1);
for (int i=0; i<n; i++) // 输出排序好的结果
{ cout<<a[i]<< " " ;
} cout<<endl;
end=clock();
printf( "The time is %6.3f"
,( double )(end-start-over)/CLK_TCK); // 显
示运行时间
cout<<endl;
system( "pause" );
return 0;
}
template < class Type>
void S &x,Type &y) // 将两个数据交换
{
Type temp = x; x = y;
y = temp;
}
//函数产生x和y之间的一个随机整数,且产生不同整数的概率相同 inline int Random(int x, int y)
{
srand(( unsigned )time(0));
int ran_num = rand() % (y - x) + x;
return ran_num;
}
//函数Partition 以一个确定的基准元素a[p]对子数组a[p:r]进行划分
template <class Type>
int Partition(Type a[], int p, int r)
{
int i = p,j = r + 1;
Type x = a[p];
//将<x的元素交换到左边区域
//将之的元素交换到右边区域 while (true )
{
while (a[++i]<x && i<r);
while (a[--j]>x);
if (i>=j)
{ break;
}
Swap(a[i],a[j]);
}
a[p] = a[j]; // 将基准元素放在合适的位置
a[j] = x; return j;
// 通过 RandomizedPartition 函数来产生随机的划分 template <class Type> int RandomizedPartition(Type a[], int p, int r)
{
int i = Random(p,r);
Swap(a[i],a[p]);
return Partition(a,p,r);
}
template < class Type>
void RandomizedQuickSort(Type a[], int p, int r)
{
if (p<r)
{
int q = RandomizedPartition(a,p,r); RandomizedQuickSort(a,p,q-1); RandomizedQuickSort(a,q+1,r);
// 获得基准元素的位置// 对左半段排序
// 对右半段排序。

相关主题