洗牌算法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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章