201507241357_《JavaScript——合并》

 1 //merge()函数
 2 function merge(left, right){ 
 3   var result = []; 
 4   while (left.length > 0 && right.length > 0){ 
 5     if (left[0] < right[0]){ 
 6       result.push(left.shift()); 
 7     } else { 
 8       result.push(right.shift()); 
 9     } 
10   } 
11   return result.concat(left).concat(right); 
12 }; 
13 
14 
15 //mergeSort()函数
16 function mergeSort(items){ 
17   if (items.length == 1) { 
18     return items; 
19   } 
20   var middle = Math.floor(items.length / 2), 
21   left = items.slice(0, middle), 
22   right = items.slice(middle); 
23   return merge(mergeSort(left), mergeSort(right)); 
24 }; 
25 
26 //test
27 var lArr = [2,4,7,4,2,7]; 
28 var rArr = [3,6,3,8,2,9]; 
29 var newArr = merge(lArr,rArr); 
30 for(var len = newArr.length,i = len;i>=0;i--){console.log(newArr[i])};  //9,2,8,7,2,4,7,3,6,4,3,2

 

posted @ 2015-07-24 13:59  Coca-code  阅读(150)  评论(0编辑  收藏  举报