Chinaunix首页 | 论坛 | 博客
  • 博客访问: 264395
  • 博文数量: 45
  • 博客积分: 930
  • 博客等级: 准尉
  • 技术积分: 553
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-22 17:53
文章分类

全部博文(45)

文章存档

2013年(5)

2012年(40)

分类: C/C++

2012-07-18 09:29:47

算法思想来自《算法导论》

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdlib>
  4. #include <random>
  5. #include <ctime>
  6. const int SIZE = 10;
  7. using namespace std;
  8. //Data swap function
  9. void swap(int &p,int &q)
  10. {
  11.     int temp = p;
  12.     p=q;
  13.     q=temp;
  14. }

  15. //Partition function
  16. template <typename T>
  17. int Partition(vector<T> & arr,int p,int r)
  18. {
  19.     T x = arr[r];
  20.     int i = p -1;
  21.     for (int j = p; j < r;j++)
  22.     {
  23.         if(arr[j] <= x)
  24.         {
  25.             i = i+1;
  26.             swap(arr[i],arr[j]);
  27.         }
  28.     }
  29.     swap(arr[i+1],arr[r]);
  30.     return (i+1);
  31. }

  32. //Quick sort
  33. template <typename T>
  34. void Quick_sort(vector<T> & arr,int nLow,int nHigh)
  35. {
  36.     if(nLow < nHigh)
  37.     {
  38.         int nIndex=Partition(arr, nLow, nHigh);
  39.         Quick_sort(arr , nLow, nIndex-1);
  40.         Quick_sort(arr , nIndex+1, nHigh);
  41.     }
  42. }

  43. int main()
  44. {
  45.     vector<int> arr;
  46.     srand((unsigned)time(0));

  47.     for(int i = 0; i < SIZE;i++)
  48.         arr.push_back((int)rand()%(10 * SIZE));

  49.     for (int i = 0; i < SIZE;i++)
  50.         cout<<arr[i]<<" ";
  51.     cout<<endl;

  52.     Quick_sort(arr,0,SIZE-1);

  53.     for (int i = 0; i < SIZE;i++)
  54.         cout<<arr[i]<<" ";
  55.     cout<<endl;

  56.     return 0;

  57. }


阅读(1763) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

bob_hu9242012-07-19 10:50:33

maoshaqi88: 哥们这是什么编辑器编辑的代码? 这样复制过来清晰多了.....
ChinaUnix博客自带的代码插入功能可以实现这样的功能,把在C++编辑器中代码复制过来即可!

maoshaqi882012-07-18 10:28:19

哥们这是什么编辑器编辑的代码? 这样复制过来清晰多了