您的位置:首页 > 其它

完美洗牌算法

2012-11-21 00:00 211 查看
暂时没有理解清楚,主要是个置换环,但是构造的算法,感觉很牛逼

先贴上代码,留个纪念:

/*=============================================*\
完美洗牌算法:
有个长度为2n的数组{a1,a2,a3,...,an,b1,b2,b3,...,bn},
希望排序后{a1,b1,a2,b2,....,an,bn},
要求时间复杂度o(n),空间复杂度0(1)。
\*=============================================*/
#include <iostream>
#include <string>

using namespace std;

int main(){
string arr("1234567abcdefg");
int index = arr.length() / 2;
int temp = arr[index];
while(index != 1){
int tempIndex = (index + (index % 2) * (arr.length() - 1)) / 2;
arr[index] = arr[tempIndex];
index = tempIndex;
}
arr[1] = temp;
cout << arr << endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: