当前位置:   article > 正文

QuickSort_quicksort.h

quicksort.h

一、结果显示

 

 

二、QuickSort.h

  1. #include<iostream>
  2. using namespace std;
  3. template<class T>
  4. class QuickSort
  5. {
  6. private:
  7. T a[10] = {'d','a','f','c','v','b','a','g','s','z'};
  8. int size = sizeof(a);
  9. public:
  10. QuickSort()
  11. {
  12. cout<<"size = "<<size<<endl;
  13. }
  14. void QuickSort00()
  15. {
  16. T b[10];
  17. for(int i = 0; i < size; i++)
  18. b[i] = a[i];
  19. QuickSort0( b, 0, size-1);
  20. cout<<"Quick Sort>>";
  21. print(b);
  22. }
  23. void QuickSort0(T a[], int left,int right )
  24. {
  25. if(left < right)
  26. {
  27. T pivot = median( a, left, right);
  28. int i = left,j = right-1;
  29. for( ; ; )
  30. {
  31. while(a[++i] < pivot) {}
  32. while(pivot < a[--j]) {}
  33. if(i < j) //Repeat until i > j ;
  34. swap(a[i], a[j]);
  35. else
  36. break;
  37. }
  38. swap(a[i], a[right-1]); //The bigger at Position "i" !!!
  39. QuickSort0( a, left, i-1);
  40. QuickSort0( a, i+1, right);
  41. }
  42. }
  43. const T & median(T a[], int left,int right)
  44. {
  45. int center = (left + right)/2;
  46. if(a[left] > a[center])
  47. swap(a[left], a[center]);
  48. if(a[center] > a[right])
  49. swap(a[center], a[right]);
  50. if(a[left] > a[right])
  51. swap(a[right], a[left]);
  52. swap(a[center], a[right-1]); //Place the pivot at right-1 , the right is biggest !!
  53. return a[right-1];
  54. }
  55. void vprint()
  56. {
  57. cout<<"The original char array is : ";
  58. print(a);
  59. }
  60. void print(char a[10])
  61. {
  62. for(int i = 0 ; i < size ; i++)
  63. {
  64. cout<<a[i]<<" ";
  65. }
  66. cout<<endl;
  67. }
  68. };

 

三、main.cpp

  1. #include "QuickSort.h"
  2. using namespace std;
  3. int main()
  4. {
  5. QuickSort<char> T;
  6. T.vprint();
  7. T.QuickSort00();
  8. cout << "Hello world!" << endl;
  9. return 0;
  10. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/640455
推荐阅读
相关标签
  

闽ICP备14008679号