1、数据结构程序报告(5)1. 需求分析:(1)堆排序、快速排序、基数排序(静态链表)输出一组数组【1】堆排序: 对所有纪录建立最大堆 1取出堆顶的最大纪录与数组末端的纪录交换,最大记录在下边 n-1 的 2位置,原数组末端元素临时处于根结点;将根元素向下调整到合适的位置,即剩下的 n-1个记录重新调整为堆,再取新堆顶最大的记录,与数组 n-2 为交换;不断重复这一操作,直到堆为空。这时数组正好是从小到大排序。【2】快速排序: 从待排序序列 S 中任意选择一个记录 k 作为轴值。 1将剩余的记录分割成左子序列 L 和右子序列 R。 2L 中所有记录都小于或等于 k,R 中记录都大于等于 k,因此
2、k 正好 3位于正确的位置。对子序列 L 和 R 递归进行快速排序,直到子序列中只含有 0 或 1 个 4元素,推出递归。【3】 基数排序: 高位优先法(MSD)分配排序。 1低位优先法(LSD)分配排序。 2从最低位 k0 开始排序,对于排好的序列再用次低位 k1 排序,依次重复,直至对最高位 kd-1 排好序后,整个序列成为有序的。这是一个分、收;分、收 .的过程。(2)输入输出要求: 输入数组个数:输入数组:快速排序:输入数组个数:输入数组:堆排序:输入数组个数:输入数组:基数排序:2. 算法设计: (1) QuickSort()快速排序函数, Array 为待排序数组,left、rig
3、ht 分别为数组两端,选择轴值 p,分割前先将轴值放到数组末端,分割后轴值到达正确位置,对轴值左边和右边的子序列进行递归快速排序。(2) swap()交换 2 个数。(3) Partition()分割函数,定义 l 为左指针,r 为右指针,开始分割 l、r 不断向中间移动,直到相遇。(4) MaxHeap()最大堆类定义,包括 BuildHeap()建堆,LeftChild ()返回左孩子位置,Shiftdown ()从 left 开始向下筛选,RemoveMax() 堆顶删除最大值(5) sort()堆排序,依次找出最大记录,即堆顶。(6) radixsort()静态链实现基数排序, n 为
4、数组长度, d 为排序码个数,r 为基数。(7) distribute()分配过程,A 中存放待排序记录, first 为静态链中的第一个记录,i 为第 i 个排序码,r 为基数。(8) collect()收集过程,Arra 中存放待排序记录,first 为静态链中的第一个记录,r为基数。(9) addrsort()限行时间整理静态链表,使得数组按下标有序。附程序:#include#include #include using namespace std;#define MAX 100templatevoid QuickSort(Record Array,int left,int right)
5、 /快速排序if (rightvoid swap(Record Array,int p,int right) /交换两个数Record temp;temp=p;p=right;right=temp;template int Partition(Record Array,int left,int right) /分割函数 int l=left;int r=right;Record TempRecord=Arrayr; while(l!= r) while(Arrayl=TempRecordint CurrentSize;MaxHeap(T *Array,int n);void BuildHeap
6、();int LeftChild(int pos);void Siftdown(int left); T;templateMaxHeap:MaxHeap(T *Array,int n) /构造函数if(nvoid MaxHeap:BuildHeap() /建堆for(int i=CurrentSize/2-1;i=0;i-)Siftdown(i);templateint MaxHeap:LeftChild(int pos) /返回左孩子return 2*pos+1;templatevoid MaxHeap:Siftdown(int left) /从 left 开始想向下筛选int i=left
7、;int j=LeftChild(i);T temp=heapArrayi;while(jTreturn heapArrayCurrentSize;template void sort(Record Array,int n) /堆排序 MaxHeap max_heap=MaxHeap(Array,n); /依次找出最大记录for(int i=0; i /静态链实现基数排序,n 为数组长度,d 为排序码个数,r 为基数void radixsort(Record *arra,int n,int d,int r)int i,first=0;staticqueue *queue=new staticq
8、ueuer;for(i=0;ivoid distribute(Record *arra,int first,int i,int r,staticqueue *queue)int j,k,a,curr=first;for(j=0;jvoid collect(Record *arra,intwhile(queuek.head=-1)k+;first=queuek.head;last=queuek.tail;while(kvoid addrsort(Record *arra,int n,int first)int i,j;j=first;Record temprec;for(i=0;in;array
9、=new intn;coutarrayi;QuickSort(array,0,n-1);coutm;array=new intm;coutarrayi;sort(array,m);coutk;Record *arra=new Recordk;coutarrak.key;radixsort(arra,k,2,10);cout“基数排序:“;for(i=0;ik;i+)coutarrai.key“ “;system(“pause“);3. 测试截图:4. 总结:程序调试中的问题及解决方法:快速排序直接运用书上的算法,堆排序在建堆的过程需要修改书上的最小堆建立方法,基数排序运用书上的算法也可以很快的编出程序,总的来说这次上机题不算太难 心得体会: 经过这次编程,我意识到了数据结构这本书的重要性,有很多算法背很难背下来,这种工具书就是用来查资料的,具体的算法都在书上,直接用到程序中就 ok 了,还有就是对各种排序方法有了更深的理解