Ported Next Permutation Algorithm from c++