JavaScript algorithm, Python algorithm, go algorithm, Java algorithm, series of "merge Sort" chapter

Source: Internet
Author: User

Common internal sorting algorithms are: Insert sort, hill sort, select sort, bubble sort, merge sort, quick sort, heap sort, cardinality sort, etc. Summarize with a picture:


650) this.width=650; "Src=" https://s4.51cto.com/wyfs02/M02/95/7B/wKioL1kVgaOibmjiAANCkj6aEBI037.png-wh_500x0-wm_ 3-wmp_4-s_2406916609.png "title=" 1513609480-59142359dda6f_articlex.png "alt=" Wkiol1kvgaoibmjiaanckj6aebi037.png-wh_50 "/>


merge sort (English: Merge sort, or mergesort) is an efficient sorting algorithm for creating a merge operation with an efficiency of O (n log n). It was first presented by John von Neumann in 1945. The algorithm is a very typical application of divide-and-conquer method (Divide and Conquer), and the recursion of each layer can be carried out simultaneously.


650) this.width=650; "Src=" Https://s2.51cto.com/wyfs02/M01/95/7B/wKioL1kVgdXQJ8-fAACgu50ZgtI663.png-wh_500x0-wm _3-wmp_4-s_1989658535.png "title=" 698676359-5915791dc7f34_articlex.png "alt=" Wkiol1kvgdxqj8-faacgu50zgti663.png-wh_50 "/>


as a typical algorithm application of divide and conquer thought, the implementation of merge sort is two ways:

top-down recursion (all recursive methods can be rewritten with iterations, so there's a 2nd approach);
Bottom-up iterations;
in the data structure and algorithm JavaScript description, the author gives a bottom-up iterative approach. But for recursion, the author argues that:
However, it's not possible-do-in-JavaScript, as the recursion goes too deep for the language to H Andle.
However, this approach is not feasible in JavaScript because the recursive depth of the algorithm is too deep for it.
to tell you the truth, I don't quite understand this remark. Does it mean that the JavaScript compiler has too little memory and is too recursive to be too deep to cause memory overflow? Also hope that the great God can teach.
As with select Sort, the performance of the merge sort is not affected by the input data, but behaves much better than the selection, because the time complexity of O (NLOGN) is always. The cost is that additional memory space is required.

    1. algorithm steps

    2. The space is applied to the sum of two sorted sequences, which is used to hold the merged sequence,

    3. set two pointers, The initial position is the starting position of two sorted sequences,

    4. Compare the elements pointed to by two pointers, select a relatively small element into the merge space, And move the pointer to the next position;

    5. Repeat step 3 until a pointer reaches the end of the sequence;

    6. Copies all the remaining elements of another sequence directly to the end of the merge sequence.

    7. action diagram Demo

650) this.width=650; "Src=" https://s4.51cto.com/wyfs02/M00/95/7B/wKiom1kVgh2iycONAABQ8QHixJ4678.png-wh_500x0-wm_ 3-wmp_4-s_3543841057.png "title=" 440427741-591423a6c9b90_articlex.png "alt=" Wkiom1kvgh2iyconaabq8qhixj4678.png-wh_50 "/>



1. JavaScript Code Implementation


Function mergesort (arr)  {      var len = arr.length;     if (len < 2)  {        return  arr;    }    var middle = math.floor (len / &NBSP;2),         left = arr.slice (0, middle),         right = arr.slice (middle);     return  merge (MergeSort (left),  mergesort (right));} Function merge (left, right) {    var result = [];     while  (left.length && right.length)  {         if  (left[0] <= right[0])  {             result.push (Left.shift ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;  } else {             Result.push (Right.shift ());        }    }     while  (left.length)         result.push ( Left.shift ());    while  (right.length)          result.push (Right.shift ());     return result;}


2. Python Code Implementation


Def mergesort (arr):     import math    if (arr) <2):         return arr    middle =  Math.floor (len (arr)/2)     left, right = arr[0:middle], arr[middle:]     return merge (MergeSort (left),  mergesort (right)) Def merge (left,right):     result = []    while left and right:         if left[0] <= right[0]:             result.append (Left.pop (0));         else:             Result.append (Right.pop (0));    while left:         result.append (Left.pop (0));    while right:        result.append (Right.pop (0));     return result


3. Go Code Implementation


Func mergesort (Arr []int)  []int {        length  := len (arr)         if length < 2 {                 return  Arr        }        middle  := length / 2        left := arr[0: middle]        right := arr[middle:]         return merge (MergeSort (left),  mergesort (right))}func merge (left [] Int, right []int)  []int {        var result  []int        for len (left)  != 0 &&  len (right)  !=  0 {                if  left[0] <= right[0] {                         result = append ( Result, left[0])                          left = left[1:]                 } else {                          result = append (result, right[0])                          right  = right[1:]                }         }        for len (left)  != 0  {                result  = append (result, left[0])                  left = left[1:]        }         for len (right)  != 0 {                 result = append (Result,  right[0])                  right = right[1:]        }         return  result} 


4.Java Implementation


 public static int[] sort (Int[] nums, int low, int high)  {         int mid =  (Low + high)  / 2;         if  (Low < high)  {                     sort ( Nums, low, mid);                    sort (Nums, mid + 1, high);             merge (Nums, low, mid, high);         }        return nums;     }    /**     *  sort the number of low to high positions in the array       * nums  Array to sort      * low  start position to queue      *  mid   Pending Center position      *  high  pending end position      */     public static void merge (int[] nums, int low, int  Mid, int high)  {        int[] temp = new  int[high - low + 1];        int i  = low;        int j = mid + 1;         int k = 0;         while  (I <= mid && j <= high)  {             if  (Nums[i] < nums[j])  {                 temp[k++] = nums[i++];             } else {                 temp[k++] = nums[j++];             }        }         while  (I <= mid)  {             temp[k++] = nums[i++];         }        while  (J <= high)  {            temp[k++] = nums[j++] ;        }               for  (int k2 = 0; k2 < temp.length; k2++)  {             nums[k2 + low] = temp[k2];         }    }


Hope to communicate with the technology, there is interest can add QQ invite into the group: 525331804 full stack technology development QQ Group: 581993430

This article is from the "Technology-aware" blog, so be sure to keep this source http://liuzhiying.blog.51cto.com/5850988/1925143

JavaScript algorithm, Python algorithm, go algorithm, Java algorithm, series of "merge Sort" chapter

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.