#include<stdio.h>
typedef struct Element
{
//向左为1 向右为0
bool direction;
//活动状态为1 非活动状态为0
bool isActive;
int data;
} ele;
void swap(ele *a,ele *b)
{
ele temp = {0,0,0};
temp = *a;
*a = *b;
*b = temp;
}
int main(void)
{
ele num[4] =
{
{1,0,1},
{1,0,2},
{1,0,3},
{1,0,4}
};
//用作交换 数据的暂时变量
ele temp = {0,0,0};
int size = sizeof(num)/sizeof(ele);
int i;
int max = 0;//活动数中最大的数
int max_pos = 0;//活动数中最大数的下标
int count = 0;
for(i = 0;i < size;i++)
{
printf("%d",num[i].data);
}
puts("");
while(1)
{
//找出 所有序列中的活动数 标记isActive = 1
for(i = 0;i < size;i++)
{
if(num[i].direction == 1)
{
if(i-1 < 0)
{
continue;
}
else
{
if(num[i-1].data < num[i].data)
{
count++;
num[i].isActive = 1;
}
}
}
else
{
if(i+1 > size)
{
continue;
}
else
{
if(num[i+1].data < num[i].data)
{
count++;
num[i].isActive = 1;
}
}
}
}
if(count == 0)
{
break;
}
for(i = 0;i < size;i++)
{
if(num[i].isActive == 1)
{
if(num[i].data > max)
{
max = num[i].data;
max_pos = i;
}
}
}
if(num[max_pos].direction == 1)
{
swap(&num[max_pos-1],&num[max_pos]);
}
else
{
swap(&num[max_pos],&num[max_pos+1]);
}
for(i = 0;i < size;i++)
{
if(num[i].data > max)
{
num[i].direction = 1-num[i].direction;
}
}
//将活动数初始化
for(i = 0;i < size;i++)
{
printf("%d",num[i].data);
num[i].isActive = 0;
}
printf("\n");
//活动数个数初始化
count = 0;
max = 0;
}
return 0;
}
C语言实现组合数学 邻位互换生成算法
最新推荐文章于 2021-05-24 09:55:35 发布