Guest User

Untitled

a guest
Nov 19th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. #include <algorithm>
  2. #include <cassert>
  3. #include <iostream>
  4. #include <random>
  5. #include <vector>
  6.  
  7. template <class RandomAccessIterator>
  8. void quick_sort(RandomAccessIterator begin, RandomAccessIterator end) {
  9. // 要素数0, 1の場合
  10. if (begin == end || begin + 1 == end) {
  11. return;
  12. }
  13. // 要素数2の場合
  14. if (begin + 2 == end) {
  15. if (*begin < *(begin + 1)) {
  16. return;
  17. } else {
  18. std::iter_swap(begin, begin + 1);
  19. return;
  20. }
  21. }
  22. // 要素数3以上の場合
  23. auto l = begin;
  24. auto r = end - 1;
  25. auto pivot = std::max({*l, *(l + 1), *(l + 2)});
  26. while (true) {
  27. while (*l < pivot) {
  28. ++l;
  29. }
  30. while (pivot < *r) {
  31. --r;
  32. }
  33. if (l < r) {
  34. std::iter_swap(l, r);
  35. ++l;
  36. --r;
  37. } else {
  38. break;
  39. }
  40. }
  41. quick_sort(begin, l);
  42. quick_sort(l, end);
  43. }
  44.  
  45. int main() {
  46. // ユニットテストとテスト出力
  47. {
  48. std::vector<int> v = {6, 7, 8, 5, 9, 3, 1, 4, 8, 2, 2, 2, 0};
  49. quick_sort(v.begin(), v.end());
  50. if(!std::is_sorted(v.begin(), v.end())) {
  51. assert(false);
  52. }
  53. for (auto a : v) {
  54. std::cout << a << ", ";
  55. }
  56. std::cout << std::endl;
  57. }
  58.  
  59. // ランダムテスト
  60. std::random_device seed_gen;
  61. std::mt19937 engine(seed_gen());
  62. std::uniform_int_distribution<> dist(0, 100);
  63. for (int i = 0; i < 1000; ++i) {
  64. std::vector<int> v;
  65. for (int j = 0; j < 1000; ++j) {
  66. v.push_back(dist(engine));
  67. }
  68. quick_sort(v.begin(), v.end());
  69. if(!std::is_sorted(v.begin(), v.end())) {
  70. for (auto a : v) {
  71. std::cout << a << ", ";
  72. }
  73. assert(false);
  74. }
  75. }
  76. std::cout << std::endl;
  77.  
  78. std::cout << "success" << std::endl;
  79. }
Add Comment
Please, Sign In to add comment