Write a merge sort program
Posted primerplus
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Write a merge sort program相关的知识,希望对你有一定的参考价值。
Merge Sort- Recursion
Write a merge sort program in javascript.
Sample array : [34, 7, 23, 32, 5, 62]
Sample output : [5, 7, 23, 32, 34, 62]
Pictorial Presentation:
Sample Solution:
Array.prototype.merge_Sort = function () {
if (this.length <= 1)
{
return this;
}
let half = parseInt(this.length / 2);
let left = this.slice(0, half).merge_Sort();
let right = this.slice(half, this.length).merge_Sort();
let merge = function (left, right) {
let arry = [];
while (left.length > 0 && right.length > 0) {
arry.push((left[0] <= right[0]) ? left.shift() : right.shift());
}
return arry.concat(left).concat(right);
};
return merge(left, right);
};
let arr = [34,7,23,32,5,62];
console.log(arr.merge_Sort());
Flowchart:
以上是关于Write a merge sort program的主要内容,如果未能解决你的问题,请参考以下文章