1 /*
2     Copyright 2005-2014 Intel Corporation.  All Rights Reserved.
3 
4     This file is part of Threading Building Blocks. Threading Building Blocks is free software;
5     you can redistribute it and/or modify it under the terms of the GNU General Public License
6     version 2  as  published  by  the  Free Software Foundation.  Threading Building Blocks is
7     distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
8     implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9     See  the GNU General Public License for more details.   You should have received a copy of
10     the  GNU General Public License along with Threading Building Blocks; if not, write to the
11     Free Software Foundation, Inc.,  51 Franklin St,  Fifth Floor,  Boston,  MA 02110-1301 USA
12 
13     As a special exception,  you may use this file  as part of a free software library without
14     restriction.  Specifically,  if other files instantiate templates  or use macros or inline
15     functions from this file, or you compile this file and link it with other files to produce
16     an executable,  this file does not by itself cause the resulting executable to be covered
17     by the GNU General Public License. This exception does not however invalidate any other
18     reasons why the executable file might be covered by the GNU General Public License.
19 */
20 
21 #ifndef __TBB_parallel_sort_H
22 #define __TBB_parallel_sort_H
23 
24 #include "parallel_for.h"
25 #include "blocked_range.h"
26 #include "internal/_range_iterator.h"
27 #include <algorithm>
28 #include <iterator>
29 #include <functional>
30 
31 namespace tbb {
32 
33 //! @cond INTERNAL
34 namespace internal {
35 
36 //! Range used in quicksort to split elements into subranges based on a value.
37 /** The split operation selects a splitter and places all elements less than or equal
38     to the value in the first range and the remaining elements in the second range.
39     @ingroup algorithms */
40 template<typename RandomAccessIterator, typename Compare>
41 class quick_sort_range: private no_assign {
42 
median_of_three(const RandomAccessIterator & array,size_t l,size_t m,size_t r)43     inline size_t median_of_three(const RandomAccessIterator &array, size_t l, size_t m, size_t r) const {
44         return comp(array[l], array[m]) ? ( comp(array[m], array[r]) ? m : ( comp( array[l], array[r]) ? r : l ) )
45                                         : ( comp(array[r], array[m]) ? m : ( comp( array[r], array[l] ) ? r : l ) );
46     }
47 
pseudo_median_of_nine(const RandomAccessIterator & array,const quick_sort_range & range)48     inline size_t pseudo_median_of_nine( const RandomAccessIterator &array, const quick_sort_range &range ) const {
49         size_t offset = range.size/8u;
50         return median_of_three(array,
51                                median_of_three(array, 0, offset, offset*2),
52                                median_of_three(array, offset*3, offset*4, offset*5),
53                                median_of_three(array, offset*6, offset*7, range.size - 1) );
54 
55     }
56 
57 public:
58 
59     static const size_t grainsize = 500;
60     const Compare &comp;
61     RandomAccessIterator begin;
62     size_t size;
63 
quick_sort_range(RandomAccessIterator begin_,size_t size_,const Compare & comp_)64     quick_sort_range( RandomAccessIterator begin_, size_t size_, const Compare &comp_ ) :
65         comp(comp_), begin(begin_), size(size_) {}
66 
empty()67     bool empty() const {return size==0;}
is_divisible()68     bool is_divisible() const {return size>=grainsize;}
69 
quick_sort_range(quick_sort_range & range,split)70     quick_sort_range( quick_sort_range& range, split ) : comp(range.comp) {
71         using std::swap;
72         RandomAccessIterator array = range.begin;
73         RandomAccessIterator key0 = range.begin;
74         size_t m = pseudo_median_of_nine(array, range);
75         if (m) swap ( array[0], array[m] );
76 
77         size_t i=0;
78         size_t j=range.size;
79         // Partition interval [i+1,j-1] with key *key0.
80         for(;;) {
81             __TBB_ASSERT( i<j, NULL );
82             // Loop must terminate since array[l]==*key0.
83             do {
84                 --j;
85                 __TBB_ASSERT( i<=j, "bad ordering relation?" );
86             } while( comp( *key0, array[j] ));
87             do {
88                 __TBB_ASSERT( i<=j, NULL );
89                 if( i==j ) goto partition;
90                 ++i;
91             } while( comp( array[i],*key0 ));
92             if( i==j ) goto partition;
93             swap( array[i], array[j] );
94         }
95 partition:
96         // Put the partition key were it belongs
97         swap( array[j], *key0 );
98         // array[l..j) is less or equal to key.
99         // array(j..r) is greater or equal to key.
100         // array[j] is equal to key
101         i=j+1;
102         begin = array+i;
103         size = range.size-i;
104         range.size = j;
105     }
106 };
107 
108 #if __TBB_TASK_GROUP_CONTEXT
109 //! Body class used to test if elements in a range are presorted
110 /** @ingroup algorithms */
111 template<typename RandomAccessIterator, typename Compare>
112 class quick_sort_pretest_body : internal::no_assign {
113     const Compare &comp;
114 
115 public:
quick_sort_pretest_body(const Compare & _comp)116     quick_sort_pretest_body(const Compare &_comp) : comp(_comp) {}
117 
operator()118     void operator()( const blocked_range<RandomAccessIterator>& range ) const {
119         task &my_task = task::self();
120         RandomAccessIterator my_end = range.end();
121 
122         int i = 0;
123         for (RandomAccessIterator k = range.begin(); k != my_end; ++k, ++i) {
124             if ( i%64 == 0 && my_task.is_cancelled() ) break;
125 
126             // The k-1 is never out-of-range because the first chunk starts at begin+serial_cutoff+1
127             if ( comp( *(k), *(k-1) ) ) {
128                 my_task.cancel_group_execution();
129                 break;
130             }
131         }
132     }
133 
134 };
135 #endif /* __TBB_TASK_GROUP_CONTEXT */
136 
137 //! Body class used to sort elements in a range that is smaller than the grainsize.
138 /** @ingroup algorithms */
139 template<typename RandomAccessIterator, typename Compare>
140 struct quick_sort_body {
operatorquick_sort_body141     void operator()( const quick_sort_range<RandomAccessIterator,Compare>& range ) const {
142         //SerialQuickSort( range.begin, range.size, range.comp );
143         std::sort( range.begin, range.begin + range.size, range.comp );
144     }
145 };
146 
147 //! Wrapper method to initiate the sort by calling parallel_for.
148 /** @ingroup algorithms */
149 template<typename RandomAccessIterator, typename Compare>
parallel_quick_sort(RandomAccessIterator begin,RandomAccessIterator end,const Compare & comp)150 void parallel_quick_sort( RandomAccessIterator begin, RandomAccessIterator end, const Compare& comp ) {
151 #if __TBB_TASK_GROUP_CONTEXT
152     task_group_context my_context;
153     const int serial_cutoff = 9;
154 
155     __TBB_ASSERT( begin + serial_cutoff < end, "min_parallel_size is smaller than serial cutoff?" );
156     RandomAccessIterator k;
157     for ( k = begin ; k != begin + serial_cutoff; ++k ) {
158         if ( comp( *(k+1), *k ) ) {
159             goto do_parallel_quick_sort;
160         }
161     }
162 
163     parallel_for( blocked_range<RandomAccessIterator>(k+1, end),
164                   quick_sort_pretest_body<RandomAccessIterator,Compare>(comp),
165                   auto_partitioner(),
166                   my_context);
167 
168     if (my_context.is_group_execution_cancelled())
169 do_parallel_quick_sort:
170 #endif /* __TBB_TASK_GROUP_CONTEXT */
171         parallel_for( quick_sort_range<RandomAccessIterator,Compare>(begin, end-begin, comp ),
172                       quick_sort_body<RandomAccessIterator,Compare>(),
173                       auto_partitioner() );
174 }
175 
176 } // namespace internal
177 //! @endcond
178 
179 /** \page parallel_sort_iter_req Requirements on iterators for parallel_sort
180     Requirements on value type \c T of \c RandomAccessIterator for \c parallel_sort:
181     - \code void swap( T& x, T& y ) \endcode        Swaps \c x and \c y
182     - \code bool Compare::operator()( const T& x, const T& y ) \endcode
183                                                     True if x comes before y;
184 **/
185 
186 /** \name parallel_sort
187     See also requirements on \ref parallel_sort_iter_req "iterators for parallel_sort". **/
188 //@{
189 
190 //! Sorts the data in [begin,end) using the given comparator
191 /** The compare function object is used for all comparisons between elements during sorting.
192     The compare object must define a bool operator() function.
193     @ingroup algorithms **/
194 template<typename RandomAccessIterator, typename Compare>
parallel_sort(RandomAccessIterator begin,RandomAccessIterator end,const Compare & comp)195 void parallel_sort( RandomAccessIterator begin, RandomAccessIterator end, const Compare& comp) {
196     const int min_parallel_size = 500;
197     if( end > begin ) {
198         if (end - begin < min_parallel_size) {
199             std::sort(begin, end, comp);
200         } else {
201             internal::parallel_quick_sort(begin, end, comp);
202         }
203     }
204 }
205 
206 //! Sorts the data in [begin,end) with a default comparator \c std::less<RandomAccessIterator>
207 /** @ingroup algorithms **/
208 template<typename RandomAccessIterator>
parallel_sort(RandomAccessIterator begin,RandomAccessIterator end)209 inline void parallel_sort( RandomAccessIterator begin, RandomAccessIterator end ) {
210     parallel_sort( begin, end, std::less< typename std::iterator_traits<RandomAccessIterator>::value_type >() );
211 }
212 
213 //! Sorts the data in rng using the given comparator
214 /** @ingroup algorithms **/
215 template<typename Range, typename Compare>
parallel_sort(Range & rng,const Compare & comp)216 void parallel_sort(Range& rng, const Compare& comp) {
217     parallel_sort(tbb::internal::first(rng), tbb::internal::last(rng), comp);
218 }
219 
220 //! Sorts the data in const rng using the given comparator
221 /** @ingroup algorithms **/
222 template<typename Range, typename Compare>
parallel_sort(const Range & rng,const Compare & comp)223 void parallel_sort(const Range& rng, const Compare& comp) {
224     parallel_sort(tbb::internal::first(rng), tbb::internal::last(rng), comp);
225 }
226 
227 //! Sorts the data in rng with a default comparator \c std::less<RandomAccessIterator>
228 /** @ingroup algorithms **/
229 template<typename Range>
parallel_sort(Range & rng)230 void parallel_sort(Range& rng) {
231     parallel_sort(tbb::internal::first(rng), tbb::internal::last(rng));
232 }
233 
234 //! Sorts the data in const rng with a default comparator \c std::less<RandomAccessIterator>
235 /** @ingroup algorithms **/
236 template<typename Range>
parallel_sort(const Range & rng)237 void parallel_sort(const Range& rng) {
238     parallel_sort(tbb::internal::first(rng), tbb::internal::last(rng));
239 }
240 
241 //! Sorts the data in the range \c [begin,end) with a default comparator \c std::less<T>
242 /** @ingroup algorithms **/
243 template<typename T>
parallel_sort(T * begin,T * end)244 inline void parallel_sort( T * begin, T * end ) {
245     parallel_sort( begin, end, std::less< T >() );
246 }
247 //@}
248 
249 
250 } // namespace tbb
251 
252 #endif
253 
254