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;
}``````
2
Contributors
1
2
Views
8 Years
Discussion Span