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

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

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:

Merge sort (English: merge sort, or mergesort) is an efficient sorting algorithm that creates an O (n log n) on a merge operation. 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.

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 is a 2nd method);
Bottom-up iterations;
In the "Data structure and algorithm JavaScript description", the author gives a bottom-up iterative method. But for the recursive method, the author thinks:
However, it is not possible to do so in JavaScript, as the recursion goes too deep for the language to handle.
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, since it is always the time complexity of O (NLOGN). 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 store 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. Motion Diagram Demo

1. JavaScript Code Implementation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

functionmergeSort(arr) {  

    varlen = arr.length;

    if(len < 2) {

        returnarr;

    }

    varmiddle = Math.floor(len / 2),

        left = arr.slice(0, middle),

        right = arr.slice(middle);

    returnmerge(mergeSort(left), mergeSort(right));

}

functionmerge(left, right){

    varresult = [];

    while(left.length && right.length) {

        if(left[0] <= right[0]) {

            result.push(left.shift());

        else{

            result.push(right.shift());

        }

    }

    while(left.length)

        result.push(left.shift());

    while(right.length)

        result.push(right.shift());

    returnresult;

}

2. Python Code Implementation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

defmergeSort(arr):

    importmath

    if(len(arr)<2):

        returnarr

    middle =math.floor(len(arr)/2)

    left, right =arr[0:middle], arr[middle:]

    returnmerge(mergeSort(left), mergeSort(right))

defmerge(left,right):

    result =[]

    whileleft andright:

        ifleft[0] <=right[0]:

            result.append(left.pop(0));

        else:

            result.append(right.pop(0));

    whileleft:

        result.append(left.pop(0));

    whileright:

        result.append(right.pop(0));

    returnresult

3. Go Code Implementation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

func mergeSort(arr []int) []int {

        length := len(arr)

        iflength < 2 {

                returnarr

        }

        middle := length / 2

        left := arr[0:middle]

        right := arr[middle:]

        returnmerge(mergeSort(left), mergeSort(right))

}

func merge(left []int, right []int) []int {

        varresult []int

        forlen(left) != 0 && len(right) != 0 {

                ifleft[0] <= right[0] {

                        result = append(result, left[0])

                        left = left[1:]

                else{

                        result = append(result, right[0])

                        right = right[1:]

                }

        }

        forlen(left) != 0 {

                result = append(result, left[0])

                left = left[1:]

        }

        forlen(right) != 0 {

                result = append(result, right[0])

                right = right[1:]

        }

        returnresult

}

4. Java implementation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

 publicstatic int[] sort(int[] nums, int low, inthigh) {

        intmid = (low + high) / 2;

        if(low < high) {

        

            sort(nums, low, mid);

       

            sort(nums, mid + 1, high);

            merge(nums, low, mid, high);

        }

        returnnums;

    }

    /**

     * 将数组中low到high位置的数进行排序

     * nums 待排序数组

     * low 待排的开始位置

     *  mid 待排中间位置

     *  high 待排结束位置

     */

    publicstatic void merge(int[] nums, int low, int mid, inthigh) {

        int[] temp = newint[high - low + 1];

        inti = low;

        intj = mid + 1;

        intk = 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(intk2 = 0; k2 < temp.length; k2++) {

            nums[k2 + low] = temp[k2];

        }

    }

Login to the http://www.learnbo.com/Academy website

Or follow our official Weibo blog, and more!

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.