实验项目名称:排序
实验目的及要求:实验目的
(1)理解快速排序算法。
(2)掌握实现快速排序算法。
要求:
(1)设计一顺序表的存储结构;
(2)数据元素为整数类型;
(3)在实现顺序表的快速排序算法
实验原理:
通过一趟排序将待排序记录分割成独立的两部分,其中一部分的关键字均比另一部分的关键字小,则可分别对这两部分记录继续分别进行排序,以达到整个序列有序。
从序列的两端交替扫描各个记录,将关键字小于基准关键字的记录依次放置到序列的前边;而将关键字大于基准关键字的记录从序列的最后端起,依次放置到序列的后边,直到扫描完所有的记录。
设待排序的记录序列是R[s…t] ,在记录序列中任取一个记录(一般取R[s])作为参照(又称为基准或枢轴),以R[s].key为基准重新排列其余的所有记录。
方法是:
◆ 所有关键字比基准小的放R[s]之前;
◆ 所有关键字比基准大的放R[s]之后。
以R[s].key最后所在位置i作为分界,将序列R[s…t]分割成两个子序列,称为一趟快速排序。
实验内容(方法和步骤):
通过键盘接收数据,将数据存入顺序表中。
测试用例:(50,10,60,30,70,40,45,1,58,35,20)。
实验步骤:
(1)接收十进制整数存储到顺序表中。
(2)输出显示每一趟排序结果。
实验结果与分析:
(1)分析实验中所遇到的问题,自己的解决思路及实现方法。
(2)写出自己所用的测试用例,并记录结果。
(3)总结本次实验的收获。
#include <stdio.h>
#include "stdlib.h"
// create a search table. the function will return the length of the table.
int createSearchTable(int **s){
printf("please enter the length of the the search table.\n");
int len = 0;
scanf_s("%d", &len);
*s = (int *)malloc(sizeof(int) * len);
printf("please enter the elements:\n");
for (int i = 0; i < len; ++i) {
scanf_s("%d", (*s)+i);
}
return len;
}
void visit(int *s, int len){
// traverse the table.
printf(" the traverse of the array: ");
for (int i = 0; i < len; ++i) {
printf("%d ",*(s + i));
}
printf("\n");
}
void swap(int*s, int sp, int bigger){
// swap the two elements.
int temp = *(s + sp);
*(s + sp) = *(s + bigger);
*(s + bigger) = temp;
}
int partition(int *s, int p, int r, int len){
// before each sort, print the last result.
visit(s, len);
// pivot element. set the first element of an interval as the pivot element.
int pivot = *(s + p);
// scan pointer
int sp = p + 1;
// all elements will be lager than pivot element after the partition func.
int bigger = r;
while(sp<=bigger){
// if the element that sp points is less than pivot, sp++,else swap the two elements that sp and bigger point,and bigger--.
if(*(s+sp)<= pivot){
sp++;
}else{
swap(s, sp, bigger);
bigger--;
}
}
// swap the pivot and the bigger elements, than the pivot will be in the correct position.
// its left is smaller than its, it's right interval is bigger than it's data.
swap(s, p, bigger);
return bigger;
}
void quickSort(int *s, int p, int r, int len){
// the recursive algorithm of quick-sort.
if(p<r){
int q = partition(s, p, r, len);
quickSort(s, p, q-1, len);
quickSort(s, q+1, r, len);
}
}
int main() {
int *s = NULL;
int len = createSearchTable(&s);
printf("--------------------\n");
// test quick_sort
int p = 0;
int r = len - 1;
quickSort(s, p, r, len);
return 0;
}