How is stable_partition an adaptive algorithm?

后端 未结 3 923
一生所求
一生所求 2021-01-20 01:39

stable_partition is a function template present in algorithm header file of c++ STL. I read that it is an adaptive algorithm and its time complexity is O(n*logn) or O(n) dep

3条回答
  •  长发绾君心
    2021-01-20 02:39

    There are 2 implementations.

    1. "slower" O(n*logn) implementation
    2. "faster" O(n) implementation

    The fast implementation however needs to use a lot of memory, which may not be available. So the stable_partition asks the operating system if there is enough memory available and then chooses between the two implementations.

    Here is an example from the gcc 4.8.1 implementation with some of my comments:

    template
        _ForwardIterator
        stable_partition(_ForwardIterator __first, _ForwardIterator __last,
                 _Predicate __pred)
        {
           ...
           ...
    
           /// Try to allocate enough memory for the faster algorithm
          _Temporary_buffer<_ForwardIterator, _ValueType> __buf(__first, __last);
    
        if (__buf.size() > 0)  /// If there is enough memory
          return
            std::__stable_partition_adaptive(__first, __last, __pred,
                          _DistanceType(__buf.requested_size()),
                          __buf.begin(),
                          _DistanceType(__buf.size()));
        else  /// If there is not enough memory
          return
            std::__inplace_stable_partition(__first, __pred,
                         _DistanceType(__buf.requested_size()));
        }
    

    here std::__stable_partition_adaptive is the fast algorithm and std::__inplace_stable_partition is the slow algorithm.

提交回复
热议问题