I was trying to use Heaps algorithm the opposite way by fixing elements at the beginning of array instead of last. But Im not able to get the results. Although I understood the theory part of this algorithm, it is confusing when I am trying to implement it. Im mainly confused about the swap statements inside the if condition. (please check comment). It would be helpful if someone can tell what the problem is. Thanks for your time.

``````

function permute(string){

var str = string.split(""),strbrr = [];

function swap(strbrr,index1,index2){
var temp = strbrr[index1];
strbrr[index1] = strbrr[index2];
strbrr[index2] = temp;

}

function permuteHelper(strarr,curr,end){

if (curr == end)
console.log(strarr);
else{

var fixed  = strarr[curr];
for(i=curr;i<=end;i++){

console.log("inforbefore pH   strarr="+ strarr+" fixed="+fixed+"  i = "+i+" curr="+curr+" end = "+end);

permuteHelper(strarr,curr+1,end);
console.log("inforafter pH before swap   strarr="+strarr+" fixed="+fixed+"  i = "+i+" curr="+curr+" end = "+end);

(end+1)%2 ? swap(strarr,end,curr) : swap(strarr,i,end);    /*This is the most confusing part for me. What is the code here?*/

console.log("inforafter pH after swap   strarr="+strarr+" fixed="+fixed+"  i = "+i+" curr="+curr+" end = "+end);

}
console.log("affor   strarr="+strarr+" i="+i+" curr="+curr+" end = "+end);
}

}

permuteHelper(str,0,str.length-1);

}

var string1 = "ABCD";

permute(string1);
``````

The above line is using a ternary operator.