Question

I was curious how std:next_permutation was implemented so I extracted the the gnu libstdc++ 4.7 version and sanitized the identifiers and formatting to produce the following demo...

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

template<typename It>
bool next_permutation(It begin, It end)
{
    if (begin == end)
            return false;

    It i = begin;
    ++i;
    if (i == end)
            return false;

    i = end;
    --i;

    while (true)
    {
            It j = i;
            --i;

            if (*i < *j)
            {
                    It k = end;

                    while (!(*i < *--k))
                            /* pass */;

                    iter_swap(i, k);
                    reverse(j, end);
                    return true;
            }

            if (i == begin)
            {
                    reverse(begin, end);
                    return false;
            }
    }

}

  int main()
 {
             vector<int> v = { 1, 2, 3, 4 };

    do
    {
            for (int i = 0; i < 4; i++)
            {
                    cout << v[i] << " ";
            }
            cout << endl;
    }
    while (::next_permutation(v.begin(), v.end()));

}

My question is :

while (!(*i < *--k))
  /* Iterating linearly */;

Why cant we do a binary search instead of a naive linear iteration as the sequence from [i+1 , end) is in decreasing order ? That will increase the efficiency of search. How can a standard function in "algorithm.h" neglect such a thing which leads to better performance and efficiency ? Pls somebody explain ...

Was it helpful?

Solution

You will rarely have an array you want to permute with more than 15 elements (and actually even less), because it would require you to process 15! > 10^12 different permutations. And for arrays with such a small size binary search is less efficient than simple linear search.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top