快速排序

转自:http://blog.csdn.net/Praker/article/details/50082579?locationNum=4&fps=1

[cpp]  view plain  copy
  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. #define random(x) (rand()%x)  
  6.   
  7. struct ListNode  
  8. {  
  9.     int value;  
  10.     ListNode* next;  
  11. };  
  12.   
  13. void create_list(ListNode* head)  
  14. {  
  15.     ListNode* pNode = head;  
  16.     for(int i = 0; i < 10; i++)  
  17.     {  
  18.         ListNode* pNew = new ListNode;  
  19.         pNew->value = random(10);  
  20.         pNew->next = NULL;  
  21.   
  22.         pNode->next = pNew;  
  23.         pNode = pNode->next;  
  24.     }  
  25. }  
  26.   
  27. void print_list(ListNode* head)  
  28. {  
  29.     ListNode* pNode = head->next;  
  30.     while(pNode != NULL)  
  31.     {  
  32.         cout << pNode->value << ' ';  
  33.         pNode = pNode->next;  
  34.     }  
  35.     cout << endl;  
  36. }  
  37.   
  38. void quick_sort(ListNode* head, ListNode* tail)  
  39. {  
  40.     if(head->next == tail || head->next->next == tail)  
  41.         return;  
  42.   
  43.     ListNode* mid = head->next;  
  44.     ListNode* pLess = head;  
  45.     ListNode* pGreater = mid;  
  46.     int pivot = mid->value;  
  47.   
  48.     ListNode* pNode = mid->next;  
  49.   
  50.     while(pNode != tail)  
  51.     {  
  52.         if(pNode->value < pivot)  
  53.         {  
  54.             pLess->next = pNode;  
  55.             pLess = pNode;  
  56.         }  
  57.         else  
  58.         {  
  59.             pGreater->next = pNode;  
  60.             pGreater = pNode;  
  61.         }  
  62.   
  63.         pNode = pNode->next;  
  64.     }  
  65.   
  66.     pLess->next = mid;  
  67.     pGreater->next = tail;  
  68.   
  69.     quick_sort(head, mid);  
  70.     quick_sort(mid, tail);  
  71. }  
  72.   
  73.   
  74. int main()  
  75. {  
  76.     ListNode* head = new ListNode;  
  77.     head->value = -1;  
  78.     head->next = NULL;  
  79.       
  80.     create_list(head);  
  81.     print_list(head);  
  82.     quick_sort(head, NULL);  
  83.     print_list(head);  
  84.   
  85.     return 0;  
  86. }  



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值