fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4. #include <cinttypes>
  5.  
  6. using namespace std;
  7.  
  8. template<class T, uint8_t B>
  9. struct Hui {
  10. static void sort3_impl(vector<T> & arr);
  11. };
  12.  
  13. template<class T>
  14. struct Hui<T, 0> {
  15. static void sort3_impl(vector<T> &)
  16. {
  17. }
  18. };
  19.  
  20. template<class T>
  21. struct Hui<T, 1> {
  22. static void sort3_impl(vector<T> & arr)
  23. {
  24. swap(arr[0], arr[1]);
  25. }
  26. };
  27.  
  28. template<class T>
  29. struct Hui<T, 2> {
  30. static void sort3_impl(vector<T> & arr)
  31. {
  32. swap(arr[1], arr[2]);
  33. }
  34. };
  35.  
  36. template<class T>
  37. struct Hui<T, 5> {
  38. static void sort3_impl(vector<T> & arr)
  39. {
  40. swap(arr[0], arr[1]);
  41. swap(arr[1], arr[2]);
  42. }
  43. };
  44.  
  45. template<class T>
  46. struct Hui<T, 6> {
  47. static void sort3_impl(vector<T> & arr)
  48. {
  49. swap(arr[0], arr[2]);
  50. swap(arr[1], arr[2]);
  51. }
  52. };
  53.  
  54. template<class T>
  55. struct Hui<T, 7> {
  56. static void sort3_impl(vector<T> & arr)
  57. {
  58. swap(arr[0], arr[2]);
  59. }
  60. };
  61.  
  62. template<class T>
  63. void sort3_runtime_call(vector<T> & arr, uint8_t bits)
  64. {
  65. static array<function<void(vector<T> &)>, 8> func_table = {
  66. Hui<T, 0>::sort3_impl,
  67. Hui<T, 1>::sort3_impl,
  68. Hui<T, 2>::sort3_impl,
  69. Hui<T, 0>::sort3_impl,
  70. Hui<T, 0>::sort3_impl,
  71. Hui<T, 5>::sort3_impl,
  72. Hui<T, 6>::sort3_impl,
  73. Hui<T, 7>::sort3_impl,
  74. };
  75. func_table[bits](arr);
  76. }
  77.  
  78. template<class T>
  79. void sort3(vector<T> & arr)
  80. {
  81. sort3_runtime_call(arr, (arr[0] > arr[1]) | ((arr[1] > arr[2]) << 1) | ((arr[0] > arr[2]) << 2));
  82. }
  83.  
  84. int main()
  85. {
  86. vector<vector<uint32_t>> tests = {
  87. {1, 2, 3}, {1, 3, 2}, {2, 1, 3},
  88. {2, 3, 1}, {3, 1, 2}, {3, 2, 1},
  89. };
  90.  
  91. for (auto && arr : tests) {
  92. sort3(arr);
  93. cout << arr[0] << ", " << arr[1] << ", " << arr[2] << endl;
  94. }
  95. return EXIT_SUCCESS;
  96. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
1, 2, 3
1, 2, 3
1, 2, 3
1, 2, 3
1, 2, 3
1, 2, 3