My program is created to output permutations. Depending on the input that I put in, I sometimes get the correct result, but it is not accurate. However, when I do "abc", I get the correct result. When I input peoples names, I get a random result. After trying to figure out what is wrong, I am asking for advice on what I can do to improve my nextPermutation function, so I can get the correct results.

example input:
a
b
c

example output:

{a, b, c}
{a, c, b}
{b, a, c}
{b, c, a}
{c, a, b}
{c, b, a}

current input:

Jackie
Kevin
Eric

current output:

Jackie Kevin Eric
Kevin Eric Jackie
Kevin Jackie Eric

Program:

``````#include <iostream>
#include <algorithm>

using namespace std;

bool nextPermutation(string elements[], int n);

int main()
{

string elements[1000];
const int n = 3;

cout<<"Enter the string"<<endl;
for (int i = 0; i<n; i++)
{
cin>>elements[i];
}

do
{
cout<<elements[0]<<" "<<elements[1]<<" "<<elements[2]<<endl;
}
while (nextPermutation(elements,n));

system("PAUSE");
return 0;

}
bool nextPermutation(string elements[], int n )
{

int j = n-2;

while (j>=0 && elements[j] > elements[j+1])
{
--j;
}
if(j==-1) return false;

int k = n-1;

while (j>=0 && elements[j] > elements[k])
{
--k;
}

swap(elements[j],elements[k]);

int r = n-1;

int s = j+1;

while (r > s)
{
swap(elements[r],elements[s]);

r = r-1;

s = s+1;
}
return true;
}``````

The reason for your error is that your permutation process stops as soon as your elements are in reverse alphabetical order.

When your code permutes "b", "c", "a", it swaps to cab, then cba, then your first while loop in the permute function determines that b ([1]) is greater than a ([2]), then subtracts from j (now 0), then determines that c ([0]) is greater than b([1]) and once again subjects from j (now -1). The negative one causes the loop to end and the func to return false.

One solution to this is to sort the input into alphabetical order, then do the permutations and that should work for you.