洗牌算法

题目

有个长度为2n的数组{a1,a2,a3,…,an,b1,b2,b3,…,bn},希望排序后{a1,b1,a2,b2,….,an,bn},请考虑有无时间复杂度o(n),空间复杂度0(1)的解法。

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define  NUM 15
char * a[15] = {NULL,
"a1", "a2", "a3", "a4","a5","a6","a7",
"b1", "b2", "b3", "b4","b5","b6","b7"
};
void display_strings(char * a[], int n)
{
	for(int i = 1; i < n; ++i)
		cout << a[i] <<" ";
	cout << endl;
}
void perfect_shuffle1(char * a[], const int n)
{
    char * temp[NUM];

	for (int i = 1; i < n; ++i)
	{
		temp[2 * i % n] = a[i];	
	}	
	for (int i = 1; i < n; ++i)
	{
		a[i] = temp[i];
	}
}
int main()
{
	display_strings(a, 15);
	perfect_shuffle1(a, 15);
	display_strings(a, 15);

	return 0;
}

  

 

posted @ 2018-08-20 12:46  道微真理  阅读(98)  评论(0)    收藏  举报