全排列算法c++实现


#include <iostream>
using namespace std;
//step1: 找出最大活动整数m以及下标
int fun(int a[], int b[], int n)
{
	int max = -1;
	int value = 0;
	for (int i = 0; i<n; i++)
	{
		if ((b[i] == 0) && (i != n - 1) && (a[i]>a[i + 1]) && (a[i]>value))
		{
			max = i;
			value = a[i];
		}
		if ((b[i] == 1) && (i != 0) && (a[i]>a[i - 1]) && (a[i]>value))
		{
			max = i;
			value = a[i];
		}
	}
	return max;
}
void swap(int a[], int b[], int index, int n)
{
	//step2:交换m和其箭头所知向的与其相邻的整数
	int m = (b[index] == 1) ? (index - 1) : (index + 1);
	//交换数值
	int temp1 = a[m];
	a[m] = a[index];
	a[index] = temp1;
	//交换方向
	int temp2 = b[m];
	b[m] = b[index];
	b[index] = temp2;
	//step3:交换所有满足p>m的整数p的方向
	for (int i = 0; i<n; i++)
	{
		if (a[i]>a[m])
		{
			b[i] = 1 - b[i];
		}
	}
}
//输出函数
void display(int a[], int n)
{
	for (int i = 0; i<n; i++)
	{
		cout << a[i] << "";
	}
	cout << endl;
}
int main()
{
	int n;
	cin >> n;
	int*p = (int *)malloc(sizeof(int)*n);
	int*q = (int *)malloc(sizeof(int)*n);
	for (int i = 0; i<n; i++)
	{
		*(p + i) = i + 1;
		*(q + i) = 1;
	}
	display(p, n);
	int count = 1;
	while (fun(p, q, n) != -1)
	{
		int index = fun(p, q, n);
		swap(p, q, index, n);
		display(p, n);
		count++;
	}
	cout << "TotalNum: " << count << endl;
	free(p);
	free(q);
	system("pause");
	return 0;
}


#include<iostream>
using namespace std;
int FindMaxIndex(int a[], int n)
{
	int max = -1;
	for (int i = 0; i<n - 1; i++)
	{
		if ((a[i]<a[i + 1]) && (i>max))
		{
			max = i;
		}
	}
	return max;
}
int NewValueIndex(int a[], int n, int index)
{
	int i;
	for (i = n - 1; i>index; i--)
	{
		if (a[i]>a[index])
			break;
	}
	return i;
}
void swap(int a[], int index1, int index2)
{
	int temp = a[index1];
	a[index1] = a[index2];
	a[index2] = temp;
}
void resort(int a[], int index, int n)
{
	int r = index + 1;
	int s = n - 1;
	while (r<s)
	{
		int temp = a[r];
		a[r] = a[s];
		a[s] = temp;
		r++;
		s--;
	}
}
void display(int a[], int n)
{
	for (int i = 0; i<n; i++)
	{
		cout << a[i] << "";
	}
	cout << endl;
}
int main()
{
	int n;
	cin >> n;
	int*p = (int *)malloc(sizeof(int)*n);
	for (int i = 0; i<n; i++)
	{
		*(p + i) = i + 1;
	}
	display(p, n);
	int count = 1;
	while (FindMaxIndex(p, n) != -1)
	{
		int j = FindMaxIndex(p, n);
		int k = NewValueIndex(p, n, j);
		swap(p, j, k);
		resort(p, j, n);
		display(p, n);
		count++;
	}
	cout << "TotalNum:" << count << endl;
	free(p);
	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵卓不凡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值