/*========================================================================= # 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; }
编程练习:快速排序
最新推荐文章于 2023-07-18 17:23:34 发布