I am pretty much a beginner in c++ and wanted a little challenge so i decided to make a program to print out all permutations of a string in a lexicographic order even if the input
isn't in a lexicographic order and cant think of a solution to a problem i encountered.
the code:
#include<iostream>
#include<string>
using namespace std;
string sort(string str)
{
for (int i = 0, n = 0; n < str.length();)
{
if (str[i] > str[i + 1])
{
swap(str[i], str[i + 1]);
n = 0;
}
else
++n;
(i < (str.length() - 2)) ? ++i : i = 0;
}
return(str);
}
void premute(string str, int a)
{
int i;
if (a == (str.length()-1))
cout << str << "\n";
else
{
for (i = a; i < str.length(); ++i)
{
swap(str[a], str[i]);
premute(str, a + 1);
swap(str[a], str[i]);
}
}
}
int main()
{
string sequence;
cout << "enter a sequence of charecters\n";
cin >> sequence;
sequence = sort(sequence);
premute(sequence, 0);
cin >> sequence;
}
the problem is if i input "abc"
i get:
abc
acb
bac
bca
cba <-- out of order here
bac
and with "abcd" it is even worse.
i know that the recursion tree should print it out that way but is it possible to fix it without fancy libraries in my current code?
isn't in a lexicographic order as it should be the opposite:
cab
cba
and i have no idea how to fix it :(
+ i'm sure my string sort function isn't efficient at all and need help on simplifying it and i
don't want to use a made c/c++ library but rather create my own function to learn better and it is the challenge requirements aswell.