[Building block] Merge sort @ Python

Source: Internet
Author: User
Tags python list

Here are the basic algorithm about merge sort:

defmerge (s1,s2,s): I=j=0 whilei + J <Len (s):ifj = = Len (s2)or(I < Len (S1) andS1[i] <S2[j]): S[i+ j] =S1[i] I+ = 1Else: S[i+ j] =S2[j] J+ = 1defMerge_sort (s):"""Sort The elements of Python list s using Merge-sort algorithm"""    #Time Compelxity:o (NLOGN), where n = Len (s)n =Len (s)ifN < 2:        return    #DivideMID = N//2S1=S[:mid] S2=S[mid:]#Conquer (with recursion)Merge_sort (S1) merge_sort (S2)#Merge Resultsmerge (S1,s2,s)

Insertion sort:time Complexity:o (n^2)

defInsertion_sort (A): "" "sort list of comparable elements into nondecreasing order." "  forKinchRange (1, Len (A)):#From 1 to n-1cur = a[k]#Current element to be insertedj = k#find correct index j for current         whileJ > 0 andA[j-1] > Cur:#element A[j-1] must is after currentA[J] = a[j-1] J-= 1A[j]= cur#cur is now on the right place

[Building block] Merge sort @ Python

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.