inplace_merge.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
  3. //
  4. // Distributed under the Boost Software License, Version 1.0
  5. // See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt
  7. //
  8. // See http://boostorg.github.com/compute for more information.
  9. //---------------------------------------------------------------------------//
  10. #ifndef BOOST_COMPUTE_ALGORITHM_INPLACE_MERGE_HPP
  11. #define BOOST_COMPUTE_ALGORITHM_INPLACE_MERGE_HPP
  12. #include <iterator>
  13. #include <boost/static_assert.hpp>
  14. #include <boost/compute/system.hpp>
  15. #include <boost/compute/command_queue.hpp>
  16. #include <boost/compute/algorithm/merge.hpp>
  17. #include <boost/compute/container/vector.hpp>
  18. #include <boost/compute/type_traits/is_device_iterator.hpp>
  19. namespace boost {
  20. namespace compute {
  21. /// Merges the sorted values in the range [\p first, \p middle) with
  22. /// the sorted values in the range [\p middle, \p last) in-place.
  23. ///
  24. /// Space complexity: \Omega(n)
  25. template<class Iterator>
  26. inline void inplace_merge(Iterator first,
  27. Iterator middle,
  28. Iterator last,
  29. command_queue &queue = system::default_queue())
  30. {
  31. BOOST_STATIC_ASSERT(is_device_iterator<Iterator>::value);
  32. BOOST_ASSERT(first < middle && middle < last);
  33. typedef typename std::iterator_traits<Iterator>::value_type T;
  34. const context &context = queue.get_context();
  35. ptrdiff_t left_size = std::distance(first, middle);
  36. ptrdiff_t right_size = std::distance(middle, last);
  37. vector<T> left(left_size, context);
  38. vector<T> right(right_size, context);
  39. copy(first, middle, left.begin(), queue);
  40. copy(middle, last, right.begin(), queue);
  41. ::boost::compute::merge(
  42. left.begin(),
  43. left.end(),
  44. right.begin(),
  45. right.end(),
  46. first,
  47. queue
  48. );
  49. }
  50. } // end compute namespace
  51. } // end boost namespace
  52. #endif // BOOST_COMPUTE_ALGORITHM_INPLACE_MERGE_HPP