编程练习:快速排序

/*=========================================================================
#    FileName: QSort.c
# Description: 快速排序,输入0结束数据输入
#  LastChange: 2012-06-02 11:40:21
=========================================================================*/
#include <stdio.h>
#include <malloc.h>

struct TNode {
    int Value;
    struct TNode * next;
    struct TNode * front;
};

struct TList {
    struct TNode * head;
    /*int Length;*/
};

/* 打印链表中从begin至end的节点 */
void ptest(struct TNode *begin,struct TNode *end) {
    printf( "This is ptest!\n" );
    while(begin != end){
        printf( "%5d",begin->Value );
        begin = begin->next;
    }
    printf( "%5d\n",end->Value );
}

/* 创建链表 */
void CreatList(struct TList * T) {
    struct TNode * p1,* p2;
    T->head = NULL;
    p1 = p2 = (struct TNode *)malloc(sizeof(struct TNode));
    printf( "Please input the data!\n" );
    scanf("%d",&(p1->Value));
    while(p1->Value) {
        if(!T->head) {
            T->head = p1;
            T->head->front = NULL;
        }
        else {
            p2->next = p1;
            p1->front = p2;
            p2 = p1;
            p1 = (struct TNode *)malloc(sizeof(struct TNode));
            scanf("%d",&(p1->Value));
        }
    }
    p2->next = NULL;
}

/* 打印链表 */
void Print(struct TList *T) {
    struct TNode *h = T->head;
    while(h != NULL) {
        printf( "%5d",h->Value );
        h = h->next;
    }
    putchar('\n');
}


struct TNode * Patition( struct TNode *low, struct TNode *high ) {

    int first = low->Value;
    while(low != high) {
        while(high->Value >= first && low != high) high = high->front;
        if(low != high){
            low->Value = high->Value;
        }
        while(low->Value <= first && low != high) low = low->next; /*这个while不能与前面的while对调*/ 
        if(low != high){
            high->Value = low->Value;
        }
    }
    low->Value = first;
    return low;
}


void QuickSort( struct TNode *low, struct TNode *high) {
    struct TNode * mediate;
    mediate = Patition(low, high);
    if(mediate != low)
        QuickSort(low, mediate->front);
    if(mediate != high)
        QuickSort(mediate->next, high );
}

void QSort( struct TList *L) {
    struct TNode * end =  L->head;
    if(L->head == NULL) printf( "Error!The list is empty!\n" );
    else {
        while(end->next != NULL) end = end->next;
        QuickSort( L->head,end);
    }
}

int main( int argc, const char *argv[] )
{

    struct TList *T = (struct TList *)malloc(sizeof(struct TList));
    CreatList(T);
    printf( "The list you input is:\n" );
    Print(T);
    QSort(T);
    printf( "The result is:\n" );
    Print(T);
    free(T);
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值