奇怪了,做全排列的时候,在交换两个数时用到algorithm中的swap函数,效率竟然比自己写一个swap的效率差,是因为大量进行调用的原因吗?求解....
full_permutation 为我写的计算全排列数量的函数,没有使用algorithm中的swap函数,
nextPerm 使用了algorithm中的next_permutation函数,
full_permutation_swap 为我写的计算全排列数量的函数,使用了algorithm中的swap函数.
#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.521275counter1: 3628800
nextPerm() time: 2.98096
counter2: 3628800
full_permutation_swap() time: 1.53132
counter3: 3628800
请按任意键继续. . .