//****************************************************************************80 void perm_next ( int n, int p[], int &rank ) //****************************************************************************80 // // Purpose: // // PERM_NEXT computes the "next" permutation. // // Example: // // RANK Permutation // // 0 0 1 2 3 // 1 0 1 3 2 // 2 0 2 1 3 // 3 0 2 3 1 // 4 0 3 1 2 // 5 0 3 2 1 // 6 1 0 2 3 // ... // 23 3 2 1 0 // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 18 July 2011 // // Author: // // John Burkardt // // Reference: // // Donald Kreher, Douglas Simpson, // Combinatorial Algorithms, // CRC Press, 1998, // ISBN: 0-8493-3988-X, // LC: QA164.K73. // // Parameters: // // Input, int N, the number of values being permuted. // N must be positive. // // Input/output, int P[N], describes the permutation. // P contains integers from 0 through N-1. // // Input/output, int &RANK, the rank. // If RANK = -1 on input, then the routine understands that this is // the first call, and that the user wishes the routine to supply // the first element in the ordering, which has RANK = 0. // In general, the input value of RANK is increased by 1 for output, // unless the very last element of the ordering was input, in which // case the output value of RANK is -1. // { int i; int i1; int i2; int j; int t; // // Return the first element. // if ( rank == -1 ) { for ( i = 0; i < n; i++ ) { p[i] = i; } rank = 0; return; } // // Seek I, the highest index for which the next element is bigger. // i = n - 2; while ( 0 <= i ) { if ( p[i] <= p[i+1] ) { break; } i = i - 1; } // // If no I could be found, then we have reach the final permutation, // N, N-1, ..., 2, 1. Time to start over again. // if ( i == -1 ) { for ( i = 0; i < n; i++ ) { p[i] = i; } rank = -1; return; } // // Otherwise, look for the the highest index after I whose element // is bigger than I's. We know that I+1 is one such value, so the // loop will never fail. // else { j = n - 1; while ( p[j] < p[i] ) { j = j - 1; } // // Interchange elements I and J. // t = p[i]; p[i] = p[j]; p[j] = t; // // Reverse the elements from I+1 to N. // i1 = i + 1; i2 = n - 1; while ( i1 < i2 ) { t = p[i1]; p[i1] = p[i2]; p[i2] = t; i1 = i1 + 1; i2 = i2 - 1; } rank = rank + 1; } return; }