Advertisement
Guest User

Untitled

a guest
Dec 18th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. template<class In>
  2. In partition(In b, In e) {
  3. // create uniform distribuiton for random engine
  4. std::uniform_int_distribution<int> rand_distribution(0, std::distance(b, e - 1));
  5.  
  6. // call static random engine to get index of random pivot
  7. tbb::spin_mutex::scoped_lock lock;
  8. lock.acquire(mutex);
  9. auto rand_pivot_index = rand_distribution(rand_engine);
  10. lock.release();
  11.  
  12. // put pivot to last place in range
  13. std::swap(*(b + rand_pivot_index), *(e - 1));
  14.  
  15. // save pivot value
  16. auto pivot = *(e - 1);
  17. auto pivotiterator = b;
  18.  
  19. // sort the range
  20. for(auto it = b; it != e - 1; ++it) {
  21. if(*it < pivot) {
  22. std::swap(*it, *pivotiterator);
  23. ++pivotiterator;
  24. }
  25. }
  26.  
  27. // put pivot to its according position and return position
  28. std::swap(*(pivotiterator), *(e - 1));
  29. return pivotiterator;
  30. }
  31.  
  32.  
  33. template<class In>
  34. void quick_sort_parallel(In b, In e) {
  35. if (b != e) {
  36. In m = partition(b, e);
  37.  
  38. // switch to different sort on worst case or smaller ranges
  39. if(std::distance(b, m) > 500) {
  40. tbb::parallel_invoke([&] { quick_sort_parallel(b, m); },
  41. [&] { quick_sort_parallel(m + 1, e); });
  42. }
  43. else
  44. merge_sort_parallel(b, e); //defined somewhere else, pretty standard
  45. }
  46. }
  47.  
  48. std::uniform_int_distribution<int> rand_distribution(0, std::distance(b, e - 1));
  49.  
  50. // call static random engine to get index of random pivot
  51. tbb::spin_mutex::scoped_lock lock;
  52. lock.acquire(mutex);
  53. auto rand_pivot_index = rand_distribution(rand_engine);
  54. lock.release();
  55.  
  56. // put pivot to last place in range
  57. std::swap(*(b + rand_pivot_index), *(e - 1));
  58.  
  59. std::uniform_int_distribution<int> rand_distribution(0, std::distance(b, e - 1));
  60.  
  61. // call static random engine to get index of random pivot
  62. int rand_pivot_index;
  63. {
  64. tbb::spin_mutex::scoped_lock lock(mutex);
  65. rand_pivot_index = rand_distribution(rand_engine);
  66. }
  67.  
  68. // put pivot to last place in range
  69. std::swap(*(b + rand_pivot_index), *(e - 1));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement