数据结构-快速排序

来源:互联网 发布:淘宝网首页翡翠吊坠 编辑:程序博客网 时间:2024/06/11 00:55

程序代码如下:

#include <stdio.h>#include <stdlib.h>#include <time.h>#define MAXSIZE 20typedef int KeyType;typedef char InfoType;//结构体定义typedef struct {    KeyType key;    InfoType otherinfo;}RedType;typedef struct {    RedType r[MAXSIZE+1];    int length;}SqList;//各个函数定义void print(SqList *L);void init(SqList *L);int Partition(SqList *L,int low,int high);void QSort(SqList *L,int low,int high);void QuickSort(SqList *L);//初始化,随机产生待排序的数组void init(SqList *L) {    int n,i;    printf("请输入待排序的元素个数:");    scanf("%d",&n);    srand(((int)time(0)));//设置随机种子    for(i=1; i<=n; i++) {        L->r[i].key = rand()%10+1;    }    L->length = n;    printf("随机产生的待排数组为:");    print(L);    printf("\n");}//输出数组元素void print(SqList *L) {    int i;    for(i=1; i<=L->length; i++) {        printf("%d ",L->r[i].key);    }    printf("\n");}//进行分趟排序int Partition(SqList *L,int low,int high) {//改进的算法    int pivotkey;    L->r[0] = L->r[low];    pivotkey = L->r[low].key;    while(low<high) {        while(low<high && L->r[high].key>=pivotkey) {        --high;        }        L->r[low] = L->r[high];        while(low<high && L->r[low].key<=pivotkey) {            ++low;        }        L->r[high] = L->r[low];    }    L->r[low] = L->r[0];    return low;}/*int Partition(SqList *L,int low,int high) {    int pivotkey;    pivotkey = L->r[low].key;    while(low<high) {        while(low<high && L->r[high].key>=pivotkey) {        --high;        }        L->r[0] = L->r[high];        L->r[high] = L->r[low];        L->r[low] = L->r[0];        while(low<high && L->r[low].key<=pivotkey) {            ++low;        }        L->r[0] = L->r[high];        L->r[high] = L->r[low];        L->r[low] = L->r[0];    }    return low;}*///递归调用 分趟进行排序void QSort(SqList *L,int low,int high) {    int pivotloc;    if(low < high) {        pivotloc = Partition(L,low,high);        QSort(L,low,pivotloc-1);        QSort(L,pivotloc+1,high);    }}//进行快速排序void QuickSort(SqList *L) {    QSort(L,1,L->length);}//主函数int main(){    SqList sq;    int k;    init(&sq);    QuickSort(&sq);    printf("排序之后的数组为:");    print(&sq);    return 0;}



0 0
原创粉丝点击