疑问:关于swap和next_permutation

奇怪了,做全排列的时候,在交换两个数时用到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.521275
counter1: 3628800


nextPerm() time: 2.98096
counter2: 3628800


full_permutation_swap() time: 1.53132
counter3: 3628800
请按任意键继续. . .



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值