C++ 程序,实现 Alexander Bogomolny 的 1 到 N 元素无序排列算法
这是一个 C++ 程序,旨在为 1 到 N 的元素实现 Alexander Bogomolny 的无序排列算法
算法
Begin function AlexanderBogomolny() to implement the Algorithms Arguments: Val[] = an array N = number of elements taken as input. K = level Body of the function: intialize l = -1 l = l+1 Val[k] = l if (l == N) Call function display(Val, N) else for i = 0 to N-1 if (Val[i] == 0) Call AlexanderBogomolny(Val, N, i) l = l - 1 Val[k] = 0 End
示例
#include<iostream> #include<iomanip> using namespace std; void display(const int *n, const int size) //to display the permutation { int i; if (n != 0) { for ( i = 0; i < size; i++) { cout<<setw(4)<<n[i]; } cout<<"\n"; } } void AlexanderBogomolny(int *Val, int N, int k) { static int l = -1; int i; //At start,Assign level to 0. l = l+1; Val[k] = l; if (l == N) display(Val, N); else for (i = 0; i < N; i++) //Assign values to the array if it is zero. if (Val[i] == 0) AlexanderBogomolny(Val, N, i); //Decrement the level after all possible permutation after that level. l = l-1; Val[k] = 0; } int main() { int i, N, cnt = 1; cout<<"Enter the value to permute first N natural numbers: "; cin>>N; int Val[N]; for (i = 0; i < N; i++) { Val[i] = 0; cnt *= (i+1); } cout<<"\nThe number of permutations possible is: "<<cnt; cout<<"\n\nPermutation using Alexander Bogomolyn's Algorithms \n"; AlexanderBogomolny(Val, N, 0); return 0; }
输出
Enter the value to permute first N natural numbers: 5 The number of permutations possible is: 120 Permutation using Alexander Bogomolyn's Algorithms 1 2 3 4 5 1 2 3 5 4 1 2 4 3 5 1 2 5 3 4 1 2 4 5 3 1 2 5 4 3 1 3 2 4 5 1 3 2 5 4 1 4 2 3 5 1 5 2 3 4 1 4 2 5 3 1 5 2 4 3 1 3 4 2 5 1 3 5 2 4 1 4 3 2 5 1 5 3 2 4 1 4 5 2 3 1 5 4 2 3 1 3 4 5 2 1 3 5 4 2 1 4 3 5 2 1 5 3 4 2 1 4 5 3 2 1 5 4 3 2 2 1 3 4 5 2 1 3 5 4 2 1 4 3 5 2 1 5 3 4 2 1 4 5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