Saturday, January 4, 2014

Finding the next permutation of a sequence

In C++ there is an easy command for finding that. If you have an array of numbers. Just include the library called algorithm and use the function next_permutation( a+x,a+y); this means find the next permutation of elements in a sequence a from x to y. Vut if you wanna know the algorithm of this just keep on reading.
   Consider these numebrs 1 2 3 4 5 . This is the first permutation of number 1 2 3 4 5 . Here are the steps of for calculating next permutation. 
1. Loop over array backwards until you find the first element which is bigger than his neighbour. Suppose that element has an index of I. 
2. Swap the elements I and I-1.
3. Sort the number between indexes I+1 and N (N is the length of our sequence).

Example
 2 3 1 5 4
The first element which is greater than its neighbour is 5. Swap 5 and 1 . We will get the following sequence
2 3 5 1 4
Sort the number from 4 to 5 .
2 3 5 1 4
This is the next permutation of the sequence 2 3 1 5 4. 

No comments:

Post a Comment