生成全排列----离散数学及其应用伪代码实现

生成{1, 2, 3, 4, 5, 6, 7, 8, 9}的全排列。

算法基于离散数学及其应用的伪代码,字典顺序


#include 

int permutation(int* a, int len);

int main(void)
{
    int ret = 1;
    int i = 0;
    int A[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (i = 0; i < 9; i ++)
    {
      printf("%d", A[i]);
    }
    printf("\n");

    while (ret)
    {
        ret = permutation(A, 9);

        for(i = 0; i < 9; i++)
        {
            printf("%d", A[i]);
        }
        printf("\n");
    }

    return 0;
}

void swap(int *a, int *b)
{
    int tmp = 0;

    tmp = *a;
    *a = *b;
    *b = tmp;
}

int permutation(int* a, int len)
{
    int i = 0;
    int j = len -2, k = len-1;
    int r = len -1, s = 0;
    int *p = a;

    while (p[j] > p[j+1])
    {
        j -= 1;
        if (j == -1)
          return 0;
    }

    while (p[j] > p[k])
        k -= 1;

    swap(&p[j], &p[k]);

    s = j+1;

    while (r > s)
    {
        swap(&p[r], &p[s]);
        r--;
        s++;
    }

    return 1;

}



你可能感兴趣的:(Data,Struct)