全排列--字典序列、递归方法c语言实现

来源:互联网 发布:写一个数组 编辑:程序博客网 时间:2024/06/03 14:00
//字典序列方法

#include <stdio.h>

int a[10],N;

void qsort(int a[],int left,int right)
{
    int i,j,temp;
    i=left;
    j=right;
    temp=a[left];
    if(left>right)
        return;
    while(i!=j)
    {
        while(a[j]>temp &&j>i)
            j--;
        if(j>i)
            a[i++]=a[j];
        while(a[i]<temp &&j>i)
            i++;
        if(j>i)
            a[j--]=a[i];
    }
    a[i]=temp;
    qsort(a,left,i-1);
    qsort(a,i+1,right);
}
int fac()  //求N的阶乘,即全排列的个数
{
    int count=1,i=2;
    while (i<=N)
    {
        count*=i;
        i++;
    }
    return count;
}

void Reverse(int m,int n)
{
    int temp;
    while (m<n)
    {
        temp=a[m];
        a[m]=a[n];
        a[n]=temp;
        m++;
        n--;
    }
}

void Output()
{
    int i;
    for (i=0;i<N;i++)
    {
        printf("%3d",a[i]);
    }
    printf("\n");
}
void Fun()
{
    int index1,index2,i,k,min,n,temp;  //index1为上述j下标,index2为上述k下标
    n=fac();

    for (k=1;k<n;k++)    //n次循环
    {
        for (index1=N-2;index1>=0;index1--)    //求index1下标
        {
            if (a[index1]<a[index1+1])
            {
                break;
            }
        }

        min=32767;
        for (i=index1+1;i<N;i++)  //求index2
        {
            if (a[i]>a[index1])
            {
                if (a[i]<min)
                {
                    min=a[i];
                    index2=i;
                }
            }
        }
        temp=a[index1];       //交换a[index1],a[index2]
        a[index1]=a[index2];
        a[index2]=temp;

        Reverse(index1+1,N-1); //逆置a[index1]到a[N-1]的数
        Output();  //输出
    }
}


int main()
{
    int i;
    while (printf("\n Please input N:  "),scanf("%d",&N)!=EOF)
    {
        printf("Please input %d numbers:\n",N);
        for (i=0;i<N;i++)
        {
            scanf("%d",&a[i]);
        }
        qsort(a,0,N-1);  //先将N个数排序
        printf("These numbers are:  \n");
        for (i=0;i<N;i++)
        {
            printf("%3d",a[i]);
        }
        printf("\n");
        Fun();
    }
    return 0;
}


//递归方法

#include <stdio.h>

void permutation(int array[], int begin, int end)
{
    int i;

    if(begin == end){
        for(i = 0; i <= end; ++i){
           printf("%d",array[i]);
        }
       printf("\n");
        return;
    } else {
        //for循环遍历该排列中第一个位置的所有可能情况
        for(i = begin; i <= end; ++i) {
            swap(array[i], array[begin]);
            permutation(array, begin + 1, end);
            swap(array[i], array[begin]);
        }
    }
}

int main(int argc, char **argv)
{
    int a[3] = {1, 2, 3};
    permutation(a, 0, sizeof(a) / sizeof(int) - 1);

    return 0;
}


0 0
原创粉丝点击