Python data structure and algorithm--merge sort

Source: Internet
Author: User

Merge sort:

Principle and implementation of C language

Reference: The implementation of the five-merge sort in vernacular classical algorithm series

1. It is easy to sort an ordered array, A and B.

2. In order to make a, B group of data in order: can be a, group B separately divided into two groups.

3. After a continuous grouping, when the divided group has only one data (orderly), merging the adjacent two groups.

This is done by first recursive decomposition of the series, and then merging the sequence to complete the merge sort .

Code excerpt from "Python algorithm"

1 #merging and sorting of array seq2 #returns the sorted array3 defmergesort (seq):4Mid = Len (seq)//25LFT, RGT =Seq[:mid], Seq[mid:]6     ifLen (LFT) > 1:lft = MergeSort (LFT)#sort half of an array7     ifLen (RGT) > 1:RGT =mergesort (RGT)8 9res = []Ten     #Lft,rgt are arranged in ascending order One      whileLfT andRgt#the left and right arrays are not empty A         ifLFT[-1] >= Rgt[-1]:#find the largest element in two arrays -Res.append (Lft.pop ())#into the result array and delete the original array elements -         Else: theRes.append (Rgt.pop ())#if pop (0) is used, the following res is not reversed, but the pop (0) time is slow -                                                 #and res is relatively fast . -     #Res starts with a descending array, which is reversed to increment - Res.reverse () +     return(LFTorRGT) + Res#before the rest of the ordered array is spelled to res -  +seq = [1,2,4,6,3,7,5,9,0,5,7] A PrintMergeSort (seq)

Python data structure and algorithm--merge sort

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.