Calculate all permutations where first and last element of the set are not changed.

243 Views Asked by At

I am writing code to calculate all the permutations of a list and for the sake of optimization, would like to find an algorithm which generates permutations without changing the first and last element of my set.

eg: {0,1,2,3,4} {0,1,3,2,4} {0,2,1,3,4} {0,2,3,1,4} {0,3,2,1,4} {0,3,1,2,4}

Currently I am using heap's algorithm on the center elements and for each permutation I have to re-add the first and last element after. This seems inefficient to me. Any advice?

1

There are 1 best solutions below

3
On

You could keep the first and last element where they are but apply Heap's algorithm to the middle, and ignore the first and last element in the algorithm.