Chinaunix首页 | 论坛 | 博客
  • 博客访问: 39591
  • 博文数量: 8
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 82
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-19 14:23
个人简介

本尊不死,尔等终究为奴...

文章分类

全部博文(8)

文章存档

2016年(1)

2015年(4)

2013年(3)

我的朋友

分类: C/C++

2016-03-03 16:04:41

一、快速排序

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include <cstdarg>
  5. #include <Windows.h>

  6. using namespace std;

  7. int test[20] = {33, 25, 20, 21, 0, 99, 21, 45, 37, 61, 55, 82, 43, 76, 9, 44, 2, 54, 13, 71};

  8. template<typename T>
  9. void MySwap(T& a, T& b)
  10. {    
  11.     T x = a;
  12.     a = b;
  13.     b = x;
  14. }

  15. template<typename T>
  16. T MyPartition(T* pList, int low, int high)
  17. {
  18.     int pivot = high;

  19.     while(low < high)
  20.     {
  21.         while(low < high && pList[low] <= pList[pivot])
  22.             ++low;
  23.         MySwap(pList[low], pList[pivot]);
  24.         pivot = low;

  25.         while(low < high && pList[high] >= pList[pivot])
  26.             --high;
  27.         MySwap(pList[pivot], pList[high]);
  28.         pivot = high;
  29.     }

  30.     return high;
  31. }


  32. template<typename T>
  33. void QuickSort(T* p, int l, int r)
  34. {
  35.     T pivot;
  36.     if(l < r)
  37.     {
  38.         pivot = MyPartition(p, l, r);

  39.         QuickSort(p, l, pivot - 1);
  40.         QuickSort(p, pivot + 1, r);
  41.     }

  42.     return;
  43. }

  44. template<typename T>
  45. void PrintArray(T* pArray, int nLen)
  46. {
  47.     for(int i = 0; i < nLen; ++i)
  48.     {
  49.         cout << pArray[i] << ' ';
  50.     }
  51.     cout << endl << endl;
  52. }

  53. int main(int argc, char const *argv[])
  54. {
  55.     //srand((unsigned)time(NULL));

  56.     int nLenth = sizeof(test) / sizeof(*test);
  57.     PrintArray(test, nLenth);
  58.     QuickSort(test, 0, nLenth - 1);
  59.     PrintArray(test, nLenth);

  60.     return 0;
  61. }
二、未完,待续
阅读(1145) | 评论(0) | 转发(0) |
0

上一篇:C++模版函数的使用

下一篇:没有了

给主人留下些什么吧!~~