Python data structures and algorithms 13th Day "merge sort"

Source: Internet
Author: User

1. Code implementation

defMerge_sort (alist):ifLen (alist) <= 1:        returnalist#two-part decompositionnum = Len (alist)/2 Left=Merge_sort (Alist[:num]) right=Merge_sort (alist[num:])#Merging    returnmerge (Left,right)defmerge (left, right):" "merge operation, combine two ordered arrays left[] and right[] into a large ordered array" "    #The subscript pointer to left and rightL, R =0, 0 result= []     whileL<len (left) andr<Len (right):ifLEFT[L] <Right[r]: Result.append (Left[l]) L+ = 1Else: Result.append (Right[r]) R+ = 1result+=left[l:] Result+=Right[r:]returnresultalist= [54,26,93,17,77,31,44,55,20]sorted_alist=mergesort (alist)Print(sorted_alist)

2. Note:

(1) Merge sort adopts the idea of first splitting and merging; recursive split to not continue split stop split, then compare, and finally recursively merge

3. Complexity of Time

Optimal time complexity: O (NLOGN)

Worst time complexity: O (NLOGN)

Stability: Stable

Python data structures and algorithms 13th Day "merge sort"

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.