完美洗牌算法(1)

题目描述;
    有一个长度为2n的数组{a1,a2,a3,...,an,b1,b2,...,bn},希望排序后变成{a1,b1,a2,b2,...an,bn}.
解法1:
位置置换算法
设定数组下标从 1开始

原始序列

A1

A2

A3

A4

B1

B2

B3

B4

数组下标

1

2

3

4

5

6

7

8

最终序列

B1

A1

B2

A2

B3

A3

B4

A4

通过对比原始序列与最终前后位置的变化
前n个元素中(1->2,2->4,2->6,4->8)
推广到一般情况,前n个元素中,第i个元素去了第2i个元素的位置
后n个元素中(5->1,6->3,7->5,8->7)
推广到一般情况,后n个元素中,第i个元素去了第2(i-n)-1= 2i-(2n+1 )=2i%(2n+1 )
综合到任意情况,任意的第i个元素都最终换到了(2i)%(2n+1)的位置
c代码如下:

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #define N 9
  4. #define swap(t,x,y) (t = (x),x = (y),y = (t))
  5. int b[N];
  6. void LocationReplace(int *a,int n)
  7. {
  8.     int i = 0,n1 = 2*n,temp = 0;
  9.     for (i = 1;i <= n1 ;i++)
  10.     {
  11.         b[(2*i)%(2*n+1)] = a[i];//这里不要写成2i,2n,忘了*
  12.     }
  13.     for (i = 1;i <= n1 ;i++ )
  14.     {
  15.         a[i] = b[i];
  16.     }
  17.     for (i = 2;i<= n1 ;i += 2 )//交换a[1]和a[2],a[3]和a[4]...
  18.     {
  19.         swap(temp,a[i-1],a[i]);
  20.     }
  21. }
  22. int main()
  23. {
  24.     int a[9] = {0,1,2,3,4,5,6,7,8};
  25.     LocationReplace(a,4);
  26.     int i = 0;
  27.     for (i = 1;i <=8;i++)
  28.     {
  29.         printf("%d ",a[i]);
  30.     }
  31.     printf("\n");
  32.     return 0;
  33. }
运行结果如下:
[root@localhost ~]# ./a.out
1 5 2 6 3 7 4 8
[root@localhost ~]#   
此程序的时间复杂度是o(n),空间复杂度也是o(n).



<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(367) | 评论(0) | 转发(0) |
0

上一篇:荷兰国旗问题

下一篇:完美洗牌算法(2)

给主人留下些什么吧!~~
评论热议
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

helloworddm

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

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

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

打赏作者

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

抵扣说明:

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

余额充值