归并排序
归并排序是建立在归并操作(即将两个的数组合并成一个有序数组)上的一种有效,稳定的排序算法,该算法是采用分治法的一个非常典型的应用。归并排序首先将数组分为若干组,然后将这些组两两归并,直到排序完成。
思路
分:把数组分成两半,再对数组进行递归操作,直到将数组分成一个一个单独的数组。 合:将单独的数组合并为有序数组,再对有序数组进行合并排序,直到合并排序完这个数组。
代码实现
Array.prototype.mergSort = function(){
const rec = (arr) => {
//分
if(arr.length === 1){ return arr; };
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0, mid);
const right = arr.slice(mid, arr.length);
const orderLeft = rec(left);
const orderRight = rec(right);
//合
const res = [];
while(orderLeft.length || orderRight.length){
if(orderLeft.length && orderRight.length){
res.push( orderLeft[0] < orderRight[0] ? orderLeft.shift() : orderRight.shift() );
}else if(orderLeft.length){
res.push(orderLeft.shift());
}else if(orderRight.length){
res.push(orderRight.shift());
}
}
return res;
}
const res = rec(this);
res.forEach((n, i) => {this[i] = n;});
}
var arr = [6,1,8,5,7,4,2,3];
arr.mergSort();
时间复杂度和稳定性
- 归并排序的时间复杂度是O(N*lgN);
- 归并排序是稳定的排序算法;