码迷,mamicode.com
首页 > 其他好文 > 详细

Write a merge sort program

时间:2020-05-20 00:25:30      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:tput   slice   wchar   output   out   prototype   har   sam   src   

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

标签:tput   slice   wchar   output   out   prototype   har   sam   src   

原文地址:https://www.cnblogs.com/PrimerPlus/p/12920577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!