Implement quicksort on bidirectional iterators

It seems pretty simple to implement quicksort using bidirectional iterators with O (NlgN) and O (lgN) times. So, what is the specific reason why it std::sort()requires random access iterators?

I read about the topic why std :: sort and partial_sort require random access iterators? . But this does not explain in which specific part of the possible implementation std::sort(), which may actually require a random access iterator in order to preserve its temporal and spatial complexity.

Possible implementation with time O (NlgN) and O (logN):

template <typename BidirIt, typename Pred>
BidirIt partition(BidirIt first, BidirIt last, Pred pred) {
  while (true) {
    while (true) {
      if (first == last) return first;
      if (! pred(*first)) break;
      ++first;
    }
    while (true) {
      if (first == --last) return first;
      if (pred(*last)) break;
    }
    iter_swap(first, last);
    ++first;
  }
}

template <typename BidirIt, typename Less = std::less<void>>
void sort(BidirIt first, BidirIt last, Less&& less = Less{}) {
  using value_type = typename std::iterator_traits<BidirIt>::value_type;
  using pair = std::pair<BidirIt, BidirIt>;
  std::stack<pair> stk;
  stk.emplace(first, last);
  while (stk.size()) {
    std::tie(first, last) = stk.top();
    stk.pop();
    if (first == last) continue;
    auto prev_last = std::prev(last);
    auto pivot = *prev_last;
    auto mid = ::partition(first, prev_last,
      [=](const value_type& val) {
        return val < pivot;
      });
    std::iter_swap(mid, prev_last);
    stk.emplace(first, mid);
    stk.emplace(++mid, last);
  }
}
+4
2

, .

, O (n 2), ( " " ), quicksort . , : , , . ( , , .) , , . , ( ).

-, quicksort , ( ). , . ( , : k O (1) k. , 10 30.) , , , ( , ).

, , , quicksort O (n 2) , . ++ , std::sort "O (n log n) ", DR713 std::sort - O (n log n) . , introsort . - heapsort - , . , , (, heapsort shellsort).

, log 2 n, ( ) . , , , , ( ). , .

, , , ; .

+7

, quicksort , , , . , .

( ), , quicksort. , .

quicksort :

, , , : , ( , , , ), , . quicksort 20% , : , , mergesort , .

BTW, : , , , ( , ).

0

Source: https://habr.com/ru/post/1627106/


All Articles