Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:40:51

0001 //////////////////////////////////////////////////////////////////////////////
0002 //
0003 // (C) Copyright Orson Peters  2017.
0004 // (C) Copyright Ion Gaztanaga 2017-2018.
0005 // Distributed under the Boost Software License, Version 1.0.
0006 // (See accompanying file LICENSE_1_0.txt or copy at
0007 // http://www.boost.org/LICENSE_1_0.txt)
0008 //
0009 // See http://www.boost.org/libs/move for documentation.
0010 //
0011 //////////////////////////////////////////////////////////////////////////////
0012 //
0013 // This implementation of Pattern-defeating quicksort (pdqsort) was written
0014 // by Orson Peters, and discussed in the Boost mailing list:
0015 // http://boost.2283326.n4.nabble.com/sort-pdqsort-td4691031.html
0016 //
0017 // This implementation is the adaptation by Ion Gaztanaga of code originally in GitHub
0018 // with permission from the author to relicense it under the Boost Software License
0019 // (see the Boost mailing list for details).
0020 //
0021 // The original copyright statement is pasted here for completeness:
0022 //
0023 //  pdqsort.h - Pattern-defeating quicksort.
0024 //  Copyright (c) 2015 Orson Peters
0025 //  This software is provided 'as-is', without any express or implied warranty. In no event will the
0026 //  authors be held liable for any damages arising from the use of this software.
0027 //  Permission is granted to anyone to use this software for any purpose, including commercial
0028 //  applications, and to alter it and redistribute it freely, subject to the following restrictions:
0029 //  1. The origin of this software must not be misrepresented; you must not claim that you wrote the
0030 //     original software. If you use this software in a product, an acknowledgment in the product
0031 //     documentation would be appreciated but is not required.
0032 //  2. Altered source versions must be plainly marked as such, and must not be misrepresented as
0033 //     being the original software.
0034 //  3. This notice may not be removed or altered from any source distribution.
0035 //
0036 //////////////////////////////////////////////////////////////////////////////
0037 
0038 #ifndef BOOST_MOVE_ALGO_PDQSORT_HPP
0039 #define BOOST_MOVE_ALGO_PDQSORT_HPP
0040 
0041 #ifndef BOOST_CONFIG_HPP
0042 #  include <boost/config.hpp>
0043 #endif
0044 #
0045 #if defined(BOOST_HAS_PRAGMA_ONCE)
0046 #  pragma once
0047 #endif
0048 
0049 #include <boost/move/detail/config_begin.hpp>
0050 
0051 #include <boost/move/detail/workaround.hpp>
0052 #include <boost/move/utility_core.hpp>
0053 #include <boost/move/algo/detail/insertion_sort.hpp>
0054 #include <boost/move/algo/detail/heap_sort.hpp>
0055 #include <boost/move/detail/iterator_traits.hpp>
0056 
0057 #include <boost/move/adl_move_swap.hpp>
0058 #include <cstddef>
0059 
0060 #if defined(BOOST_CLANG) || (defined(BOOST_GCC) && (BOOST_GCC >= 40600))
0061 #pragma GCC diagnostic push
0062 #pragma GCC diagnostic ignored "-Wsign-conversion"
0063 #endif
0064 
0065 namespace boost {
0066 namespace movelib {
0067 
0068 namespace pdqsort_detail {
0069 
0070    //A simple pair implementation to avoid including <utility>
0071    template<class T1, class T2>
0072    struct pair
0073    {
0074       pair()
0075       {}
0076 
0077       pair(const T1 &t1, const T2 &t2)
0078          : first(t1), second(t2)
0079       {}
0080 
0081       T1 first;
0082       T2 second;
0083    };
0084 
0085     enum {
0086         // Partitions below this size are sorted using insertion sort.
0087         insertion_sort_threshold = 24,
0088 
0089         // Partitions above this size use Tukey's ninther to select the pivot.
0090         ninther_threshold = 128,
0091 
0092         // When we detect an already sorted partition, attempt an insertion sort that allows this
0093         // amount of element moves before giving up.
0094         partial_insertion_sort_limit = 8,
0095 
0096         // Must be multiple of 8 due to loop unrolling, and < 256 to fit in unsigned char.
0097         block_size = 64,
0098 
0099         // Cacheline size, assumes power of two.
0100         cacheline_size = 64
0101 
0102     };
0103 
0104     // Returns floor(log2(n)), assumes n > 0.
0105     template<class Unsigned>
0106     Unsigned log2(Unsigned n) {
0107         Unsigned log = 0;
0108         while (n >>= 1) ++log;
0109         return log;
0110     }
0111 
0112     // Attempts to use insertion sort on [begin, end). Will return false if more than
0113     // partial_insertion_sort_limit elements were moved, and abort sorting. Otherwise it will
0114     // successfully sort and return true.
0115     template<class Iter, class Compare>
0116     inline bool partial_insertion_sort(Iter begin, Iter end, Compare comp) {
0117         typedef typename boost::movelib::iterator_traits<Iter>::value_type T;
0118         typedef typename boost::movelib:: iter_size<Iter>::type  size_type;
0119         if (begin == end) return true;
0120         
0121         size_type limit = 0;
0122         for (Iter cur = begin + 1; cur != end; ++cur) {
0123             if (limit > partial_insertion_sort_limit) return false;
0124 
0125             Iter sift = cur;
0126             Iter sift_1 = cur - 1;
0127 
0128             // Compare first so we can avoid 2 moves for an element already positioned correctly.
0129             if (comp(*sift, *sift_1)) {
0130                 T tmp = boost::move(*sift);
0131 
0132                 do { *sift-- = boost::move(*sift_1); }
0133                 while (sift != begin && comp(tmp, *--sift_1));
0134 
0135                 *sift = boost::move(tmp);
0136                 limit += size_type(cur - sift);
0137             }
0138         }
0139 
0140         return true;
0141     }
0142 
0143     template<class Iter, class Compare>
0144     inline void sort2(Iter a, Iter b, Compare comp) {
0145         if (comp(*b, *a)) boost::adl_move_iter_swap(a, b);
0146     }
0147 
0148     // Sorts the elements *a, *b and *c using comparison function comp.
0149     template<class Iter, class Compare>
0150     inline void sort3(Iter a, Iter b, Iter c, Compare comp) {
0151         sort2(a, b, comp);
0152         sort2(b, c, comp);
0153         sort2(a, b, comp);
0154     }
0155 
0156     // Partitions [begin, end) around pivot *begin using comparison function comp. Elements equal
0157     // to the pivot are put in the right-hand partition. Returns the position of the pivot after
0158     // partitioning and whether the passed sequence already was correctly partitioned. Assumes the
0159     // pivot is a median of at least 3 elements and that [begin, end) is at least
0160     // insertion_sort_threshold long.
0161     template<class Iter, class Compare>
0162     pdqsort_detail::pair<Iter, bool> partition_right(Iter begin, Iter end, Compare comp) {
0163         typedef typename boost::movelib::iterator_traits<Iter>::value_type T;
0164         
0165         // Move pivot into local for speed.
0166         T pivot(boost::move(*begin));
0167 
0168         Iter first = begin;
0169         Iter last = end;
0170 
0171         // Find the first element greater than or equal than the pivot (the median of 3 guarantees
0172         // this exists).
0173         while (comp(*++first, pivot));
0174 
0175         // Find the first element strictly smaller than the pivot. We have to guard this search if
0176         // there was no element before *first.
0177         if (first - 1 == begin) while (first < last && !comp(*--last, pivot));
0178         else                    while (                !comp(*--last, pivot));
0179 
0180         // If the first pair of elements that should be swapped to partition are the same element,
0181         // the passed in sequence already was correctly partitioned.
0182         bool already_partitioned = first >= last;
0183         
0184         // Keep swapping pairs of elements that are on the wrong side of the pivot. Previously
0185         // swapped pairs guard the searches, which is why the first iteration is special-cased
0186         // above.
0187         while (first < last) {
0188             boost::adl_move_iter_swap(first, last);
0189             while (comp(*++first, pivot));
0190             while (!comp(*--last, pivot));
0191         }
0192 
0193         // Put the pivot in the right place.
0194         Iter pivot_pos = first - 1;
0195         if(begin != pivot_pos)   //Avoid potential self-move
0196             *begin = boost::move(*pivot_pos);
0197         *pivot_pos = boost::move(pivot);
0198 
0199         return pdqsort_detail::pair<Iter, bool>(pivot_pos, already_partitioned);
0200     }
0201 
0202     // Similar function to the one above, except elements equal to the pivot are put to the left of
0203     // the pivot and it doesn't check or return if the passed sequence already was partitioned.
0204     // Since this is rarely used (the many equal case), and in that case pdqsort already has O(n)
0205     // performance, no block quicksort is applied here for simplicity.
0206     template<class Iter, class Compare>
0207     inline Iter partition_left(Iter begin, Iter end, Compare comp) {
0208         typedef typename boost::movelib::iterator_traits<Iter>::value_type T;
0209 
0210         T pivot(boost::move(*begin));
0211         Iter first = begin;
0212         Iter last = end;
0213         
0214         while (comp(pivot, *--last));
0215 
0216         if (last + 1 == end) while (first < last && !comp(pivot, *++first));
0217         else                 while (                !comp(pivot, *++first));
0218 
0219         while (first < last) {
0220             boost::adl_move_iter_swap(first, last);
0221             while (comp(pivot, *--last));
0222             while (!comp(pivot, *++first));
0223         }
0224 
0225         Iter pivot_pos = last;
0226         *begin = boost::move(*pivot_pos);
0227         *pivot_pos = boost::move(pivot);
0228 
0229         return pivot_pos;
0230     }
0231 
0232 
0233    template<class Iter, class Compare>
0234    void pdqsort_loop( Iter begin, Iter end, Compare comp
0235                     , typename boost::movelib:: iter_size<Iter>::type bad_allowed
0236                     , bool leftmost = true)
0237    {
0238         typedef typename boost::movelib:: iter_size<Iter>::type size_type;
0239 
0240         // Use a while loop for tail recursion elimination.
0241         while (true) {
0242             size_type size = size_type(end - begin);
0243 
0244             // Insertion sort is faster for small arrays.
0245             if (size < insertion_sort_threshold) {
0246                 insertion_sort(begin, end, comp);
0247                 return;
0248             }
0249 
0250             // Choose pivot as median of 3 or pseudomedian of 9.
0251             size_type s2 = size / 2;
0252             if (size > ninther_threshold) {
0253                 sort3(begin, begin + s2, end - 1, comp);
0254                 sort3(begin + 1, begin + (s2 - 1), end - 2, comp);
0255                 sort3(begin + 2, begin + (s2 + 1), end - 3, comp);
0256                 sort3(begin + (s2 - 1), begin + s2, begin + (s2 + 1), comp);
0257                 boost::adl_move_iter_swap(begin, begin + s2);
0258             } else sort3(begin + s2, begin, end - 1, comp);
0259 
0260             // If *(begin - 1) is the end of the right partition of a previous partition operation
0261             // there is no element in [begin, end) that is smaller than *(begin - 1). Then if our
0262             // pivot compares equal to *(begin - 1) we change strategy, putting equal elements in
0263             // the left partition, greater elements in the right partition. We do not have to
0264             // recurse on the left partition, since it's sorted (all equal).
0265             if (!leftmost && !comp(*(begin - 1), *begin)) {
0266                 begin = partition_left(begin, end, comp) + 1;
0267                 continue;
0268             }
0269 
0270             // Partition and get results.
0271             pdqsort_detail::pair<Iter, bool> part_result = partition_right(begin, end, comp);
0272             Iter pivot_pos = part_result.first;
0273             bool already_partitioned = part_result.second;
0274 
0275             // Check for a highly unbalanced partition.
0276             size_type l_size = size_type(pivot_pos - begin);
0277             size_type r_size = size_type(end - (pivot_pos + 1));
0278             bool highly_unbalanced = l_size < size / 8 || r_size < size / 8;
0279 
0280             // If we got a highly unbalanced partition we shuffle elements to break many patterns.
0281             if (highly_unbalanced) {
0282                 // If we had too many bad partitions, switch to heapsort to guarantee O(n log n).
0283                 if (--bad_allowed == 0) {
0284                     boost::movelib::heap_sort(begin, end, comp);
0285                     return;
0286                 }
0287 
0288                 if (l_size >= insertion_sort_threshold) {
0289                     boost::adl_move_iter_swap(begin,             begin + l_size / 4);
0290                     boost::adl_move_iter_swap(pivot_pos - 1, pivot_pos - l_size / 4);
0291 
0292                     if (l_size > ninther_threshold) {
0293                         boost::adl_move_iter_swap(begin + 1,         begin + (l_size / 4 + 1));
0294                         boost::adl_move_iter_swap(begin + 2,         begin + (l_size / 4 + 2));
0295                         boost::adl_move_iter_swap(pivot_pos - 2, pivot_pos - (l_size / 4 + 1));
0296                         boost::adl_move_iter_swap(pivot_pos - 3, pivot_pos - (l_size / 4 + 2));
0297                     }
0298                 }
0299                 
0300                 if (r_size >= insertion_sort_threshold) {
0301                     boost::adl_move_iter_swap(pivot_pos + 1, pivot_pos + (1 + r_size / 4));
0302                     boost::adl_move_iter_swap(end - 1,                   end - r_size / 4);
0303                     
0304                     if (r_size > ninther_threshold) {
0305                         boost::adl_move_iter_swap(pivot_pos + 2, pivot_pos + (2 + r_size / 4));
0306                         boost::adl_move_iter_swap(pivot_pos + 3, pivot_pos + (3 + r_size / 4));
0307                         boost::adl_move_iter_swap(end - 2,             end - (1 + r_size / 4));
0308                         boost::adl_move_iter_swap(end - 3,             end - (2 + r_size / 4));
0309                     }
0310                 }
0311             } else {
0312                 // If we were decently balanced and we tried to sort an already partitioned
0313                 // sequence try to use insertion sort.
0314                 if (already_partitioned && partial_insertion_sort(begin, pivot_pos, comp)
0315                                         && partial_insertion_sort(pivot_pos + 1, end, comp)) return;
0316             }
0317                 
0318             // Sort the left partition first using recursion and do tail recursion elimination for
0319             // the right-hand partition.
0320             pdqsort_loop<Iter, Compare>(begin, pivot_pos, comp, bad_allowed, leftmost);
0321             begin = pivot_pos + 1;
0322             leftmost = false;
0323         }
0324     }
0325 }
0326 
0327 
0328 template<class Iter, class Compare>
0329 void pdqsort(Iter begin, Iter end, Compare comp)
0330 {
0331    if (begin == end) return;
0332    typedef typename boost::movelib:: iter_size<Iter>::type size_type;
0333    pdqsort_detail::pdqsort_loop<Iter, Compare>(begin, end, comp, pdqsort_detail::log2(size_type(end - begin)));
0334 }
0335 
0336 }  //namespace movelib {
0337 }  //namespace boost {
0338 
0339 #if defined(BOOST_CLANG) || (defined(BOOST_GCC) && (BOOST_GCC >= 40600))
0340 #pragma GCC diagnostic pop
0341 #endif
0342 
0343 #include <boost/move/detail/config_end.hpp>
0344 
0345 #endif   //BOOST_MOVE_ALGO_PDQSORT_HPP