Javascript is easy to merge and sort due to some language features. Code for details:
01
<Script type = "text/javascript">
02
Array. prototype. mergeSort = function (){
03
Var merge = function (left, right ){
04
Var final = [];
05
While (left. length & right. length ){
06
Final. push (left [0] <= right [0]? Left. shift (): right. shift ());
07
}
08
Return final. concat (left. concat (right ));
09
};
10
11
Var len = this. length;
12
If (len <2 ){
13
Return this;
14
}
15
16
Var mid = parseInt (len/2 ),
17
_ Left = this. slice (0, mid ),
18
_ Right = this. slice (mid );
19
Return merge (_ left. mergeSort (), _ right. mergeSort ());
20
}
21
22
Var arr = [];
23
For (var I = 0; I <50; I ++ ){
24
Arr. push (Math. floor (Math. random () * 100 ));
25
}
26
Document. write ("original array is:" + arr + "<br/> ");
27
28
Console. time ("merge ");
29
Document. write ("sorted array is:" + arr. mergeSort ());
30
Console. timeEnd ("merge ");
31
</Script>
Author: Cao Chao