C ++程序,用于实现从1到N的元素的Alexander Bogomolny的无序置换算法
这是一个C++程序,用于实现从1到N的元素的AlexanderBogomolny的无序排列算法
演算法
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; //开始时,将级别分配为0。- l = l+1; Val[k] = l; if (l == N) display(Val, N); else for (i = 0; i < N; i++) //如果为零,则将值分配给数组。 if (Val[i] == 0) AlexanderBogomolny(Val, N, i); //在该级别之后的所有可能置换之后,降低该级别。 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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