EDUCODER
实验四:随机快速排序
任务说明
本关任务:编写分治法算法,实现快速排序,并使其效率稳定在O(nlogn)。
相关知识
为了完成本关任务,你需要了解实验目的和实验内容。
实验目的
(1)熟悉分治法的基本设计思想。
(2)掌握概率算法在平衡子问题中的作用。
(3)掌握快速排序问题的求解过程,掌握概率算法对快速排序问题的效率改进。
实验内容
随机快速排序问题:在快速排序问题中,如果待排序的序列本身有序(升序或降序),那么快速排序算法的效率会从O(nlogn)下降为O(n2)。使用概率算法思想改进快速排序算法,使其效率尽量趋近于最佳效率O(nlogn)。
实验原理
(1)在算法中增加随机数产生器。
(2)在快速排序进行元素分割之前,使用随机数产生器生成一个随机的元素下标,交换该下标元素和序列的第一个元素。
(3)按分治法思想进行元素分割和递归求解。
(4)由于随机数产生器实现了对待排序序列元素的随机重新排列,避免在快速排序中,受序列元素影响出现最差效率的情况。
实验步骤
(1)详细阅读问题描述,理解问题;
(2)手工求解问题,得到示例输入的预期结果;
(3)设计算法,求解问题;
(4)编写算法程序;
(5)调试、运行程序,保证程序正确输出预期结果;
(6)分析程序的运行情况及算法效率。
编程要求
仔细阅读右侧编辑器中代码框架,在Begin-End之间补充完整void QuickSort(int r[], int first, int end)函数,实现快速排序,并使其效率稳定在O(nlogn),完成后请分析你的算法效率及优缺点。
测试说明
平台会对你编写的代码进行测试,比对你输出的数值与实际正确数值,只有所有数据全部计算正确才能通过测试:
测试输入:
10 //给出10个数
82 15 77 21 39 19 24 33 98 11
预期输出:
82 15 77 21 39 19 24 33 98 11
11 15 19 21 24 33 39 77 82 98
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
//random generator
int randomx(int a, int b)
{
int r;
srand((unsigned)time(0));
r = rand() % (b - a) + a;
return r;
}
//Make a partition
int Partition(int r[], int first, int end)
{
int i, j;
int temp;
i = first; j = end; //initialize
while (i < j)
{
while (i < j && r[i] <= r[j])
j--; //The right side of the scan
if (i < j)
{
//Swap the smaller records to the front
temp = r[i];
r[i] = r[j];
r[j] = temp;
i++;
}
while (i < j && r[i] <= r[j])
i++; //The left side of the scan
if (i < j)
{
//Swap the biggest records to the tail
temp = r[i];
r[i] = r[j];
r[j] = temp;
j--;
}
}
return i; // I is the final position of the axis value record
}
//quick sort
void QuickSort(int r[], int first, int end)
{
/********** Begin **********/
//在此处填写算法代码
int h;
if (first < end)
{
h= Partition(h, first ,end);
QuickSort(r, first, h-1);
QuickSort(r, h+1, end);
}
/********** End **********/
}
void ShowArray(int r[], int first, int end)
{
int i;
for (i = first; i <= end; i++)
printf("%d ", r[i]);
printf("\n");
}
int main()
{
int n, s, t;
int r[20];
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &r[i]);
s = 1, t = n;
ShowArray(r, s, t);
QuickSort(r, s, t);
ShowArray(r, s, t);
return 0;
}