洗牌算法1-蛮力搜索

中文版本见https://github.com/lmdyyh/The-Art-Of-Programming-By-July/tree/master/ebook/zh,第35章

Topic Details:There is an array of length 2n {a1, a2, a3, ..., an, b1, b2, b3, ..., bn}, hope to be {a1, b1, a2, b2, ...., an, bn} after be sorted.Consider is there any solution with the time complexity of o(n) and space complexity of 0(1).

**Source of the subject**:This subject comes from the 2013 UC school recruit pen test,seemingly simple,the string can be sorted to what it should be by brute force,however,to achieve the time and space complexity set by the subject, we need to spend no small effort.OK,please see below,a step by step optimization.

##Solution 1、Brute force transformation

We can transform the string all according to the requirement.Be analyzed by Chen Liren,in this,the subject is explained by quoting his ideas.In order to facilitate the analysis,we take n = 4, then the subject requires us to transform

a1,a2,a3,a4,**b1,b2,b3,b4**

to

a1,b1,a2,b2,a3,b3,a4,b4

### 1.1、Step by step forward

Carefully observe the characteristics of the two sequences before and after transformation,we can do the following series of operations:

first step、determine the location of b1,i.e.let b1 exchange with a2,a3,a4:

a1,b1,a2,a3,a4,**b2,b3,b4**

second step、determine the location of b2,i.e.let b2 exchange with a3,a4:

a1,b1,a2,b2,a3,a4,**b3,b4**

third step、let b3 exchange with a4:

a1,b1,a2,b2,a3,b3,a4,b4

b4 is at the final position, without further switching.So, after these three steps, we finally get the desired sequence.However, the time complexity of this method is O (N ^ 2),We have to continue to look for other ways to see any other method to achieve the expected O (N) time complexity.

### 1.2、Intermediate exchange

Of course, in addition to the above method of letting b1,b2,b3,b4 step forward by switching itself with the preceding element, we can exchange the intermediate two elements in the sequence to achieve the purpose everytime.Still using the above example,aimming at a1,a2,a3,a4,b1,b2,b3,b4

first step、exchange the two elements of the middle,equence becomes(elements to be exchanged in bold):

**a1,a2,a3**,b1,a4,**b2,b3,b4**

second step、exchange the middle of the two pairs of elements espectively:

**a1,a2**,b1,a3,b2,a4,**b3,b4**

third step、 exchange the middle of the three pairs of elements espectively,sequence becomes:

a1,b1,a2,b2,a3,b3,a4,b4

the same as solution 1.1,the time complexity is still O (N ^ 2),we have to knock ourself out on this subject.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值