Strange, when doing the whole arrangement, when exchanging two numbers to use the SWAP function in the algorithm, the efficiency is worse than writing a swap, is it because of the large number of reasons for the call?
Full_permutation for me to calculate the total number of functions, without using the SWAP function in algorithm,
Nextperm uses the Next_permutation function in the algorithm,
Full_permutation_swap for me to calculate the total number of functions, using the SWAP function in algorithm.
#include <iostream> #include <algorithm> #include <windows.h>using namespace std; Large_integer t1,t2,tc;int arr[]={1,2,3,4,5,6,7,8,9,10},counter1=0,counter2=0,counter3=0;void begin () { QueryPerformanceFrequency (&TC); QueryPerformanceCounter (&T1);} void End () {QueryPerformanceCounter (&T2);cout<< (double) (T2. Quadpart-t1.quadpart)/tc. Quadpart<<endl;} void SW (int i,int j) {int temp=arr[i];arr[i]=arr[j];arr[j]=temp;} void full_permutation (int left,int right) {if (left==right) counter1++;else{for (int i=left;i<=right;i++) {SW (left,i ); Full_permutation (left+1,right); SW (left,i);}}} void Nextperm ()//next_permutation function {do{counter2++;} while (Next_permutation (arr,arr+10));} void Full_permutation_swap (int left,int right) {if (left==right) counter3++;else{for (int i=left;i<=right;i++) {swap (Arr[left],arr[i]); Full_permutation_swap (left+1,right); swap (arr[left],arr[i]);}} int main () {begin (); Full_permutation (0,9);cout<< "Full_permutation () Time:"; end ();cout<< "CounTer1: "<<counter1<<endl<<endl;begin (); Nextperm ();cout<<" Nextperm () Time: "; end ();cout< < "Counter2:" <<counter2<<endl<<endl;begin (); Full_permutation_swap (0,9);cout<< "Full_ Permutation_swap () Time: "; end ();cout<<" Counter3: "<<counter3<<endl;return 0;}
Test Result:
Full_permutation () time:0.521275
counter1:3628800
Nextperm () time:2.98096
counter2:3628800
Full_permutation_swap () time:1.53132
counter3:3628800
Please press any key to continue ...
Questions: About swap and next_permutation