Chinaunix首页 | 论坛 | 博客
  • 博客访问: 122032
  • 博文数量: 41
  • 博客积分: 2564
  • 博客等级: 少校
  • 技术积分: 455
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-20 19:17
文章分类

全部博文(41)

文章存档

2009年(41)

我的朋友

分类: C/C++

2009-04-13 10:10:12

经典交换算法---递归版

#include <stdio.h>

void perm(int *, int);
void swap(int *, int *);

int n, tmp;
int *buf;

int main()
{
    if(EOF != scanf("%d", &n))
    {
        buf = (int *)malloc(n * sizeof(int));
        
        for(tmp = 0; tmp < n; tmp++)
        {
            buf[tmp] = tmp + 1;
        }
        
        perm(buf, n);
    }
}

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

void perm(int *data, int len)
{
    int start;
    if(1 == len)
    {
        int tmp;
        for(tmp = 0; tmp < n; tmp++)
        {
            printf("%d ", buf[tmp]);
        }
        printf("\n");
        return;
    }
    
    for(start = 0; start < len; start ++)
    {
        swap(&data[0], &data[start]);
        perm(&data[1], len - 1);
        swap(&data[0], &data[start]);    
    }
}

交换法---非递归实现

#include <stdio.h>
#include <stdlib.h>

void output(int *, int);
void swap(int *, int *);

inline void output(int *buf, int len)
{
    int tmp;
    for(tmp = 0; tmp < len; tmp ++)
    {
        printf("%d ", buf[tmp]);
    }
    printf("\n");
}

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

int main()
{
    int *buf, n;
    int *stack;
    int lv;
    if(EOF != scanf("%d", &n))
    {
        buf = (int *)malloc(n * sizeof(int));
        stack = (int *)malloc(n * sizeof(int));
        
        for(lv = 0; lv < n; lv ++)
        {
            buf[lv] = lv + 1;
            stack[lv] = lv;
        }
        
        lv = 0;
        while(1)
        {
            if(lv < 0)
            {
                break;
            }
            
            if(n - 1 == lv)
            {
                output(buf, n);
                lv --;
                if(lv >=0)
                {
                    swap(&buf[lv], &buf[stack[lv]]);
                    stack[lv] ++;
                }
                continue;
            }
            
            if(n == stack[lv])
            {
                stack[lv] = lv;
                lv --;
                if(lv >=0)
                {
                    swap(&buf[lv], &buf[stack[lv]]);
                    stack[lv] ++;
                }
                continue;
            }
            
            swap(&buf[lv], &buf[stack[lv]]);
            lv ++;
        }
    }
}

阅读(431) | 评论(0) | 转发(0) |
0

上一篇:组合

下一篇:消除递归的方法

给主人留下些什么吧!~~