// Narayana's Algorithm // Generates the next permutation in the series, in place void GeneratePermutation(LPBYTE Elements, BYTE setSizeBytes) { // Find the largest index k such that a[k] < a[k + 1]. short k, l, largestIndex = -1; for(k = (setSize - 2); k >= 0; k--) { if(Elements[k] < Elements[k+1]) { if(k > largestIndex)largestIndex = k; } } // If no such index exists, the permutation is the last permutation. if(largestIndex == -1)return; // Find the largest index l such that a[k] < a[l]. // Since k + 1 is such an index, l is well defined and satisfies k < l. k = largestIndex; largestIndex = -1; for(l = (setSize - 1); l >= 1; l--) { if(Elements[k] < Elements[l]) { if(l > largestIndex)largestIndex = l; } } // Swap a[k] with a[l]. l = largestIndex; BYTE tmp = Elements[k]; Elements[k] = Elements[l]; Elements[l] = tmp; // Reverse the sequence from a[k + 1] up to and including the final element a[n]. ++k; l = setSizeBytes - 1; while(l > k) { tmp = Elements[k]; Elements[k] = Elements[l]; Elements[l] = tmp; ++k; --l; } }