Sorting algorithm collation (Python version)

Source: Internet
Author: User

ImportRandomImport TimedefBubble_sort (a): N=Len (a) whileN>1:       forIinchRange (n-1):        ifA[i]>a[i+1]: Temp=A[i] A[i]=a[i+1] A[i+1]=Temp N+=-1returnadefInsert_sort (a): N=Len (a) forIinchRange (1, N): forJinchRange (i):ifA[j]>A[i]: Temp=A[i]delA[i] A.insert (j,temp) Break      PrintadefSelect_sort (a): N=Len (a) forIinchRange (n-1): Minn=A[i] J=I forJinchRange (i,n):ifa[j]<=Minn:minn=A[j] k=J A[i],a[k]=Minn,a[i]PrintadefQuick_sort (a): N=Len (a)ifN<2:        returna I=0 J=n-1Pivot=A[0] whilei<J: whileI<j anda[j]>=pivot:j-=1A[i],a[j]=A[j],a[i] whileI<j anda[i]<=pivot:i+=1A[i],a[j]=A[j],a[i]returnQuick_sort (A[:i]) +[pivot]+quick_sort (a[i+1:])defMerge_sort (a): Result=[] n=Len (a)ifN<2:        returna mid=n/2b=Merge_sort (A[:mid]) C=Merge_sort (a[mid:]) I=0 J=0 whileI<mid andj<Mid:ifB[i]>C[j]: Result.append (C[j]) J+=1Else: Result.append (b[i]) I+=1result=result+b[i:]+C[j:]returnresultif __name__=='__main__': A=[]     forIinchRange (20): A.append (Random.randint (1,20))    PrintQuick_sort (a)

Fast row instability now, when the list is [5,2,4,6,1,1], Pivot is 5, and the last 1 and 5 are swapped, which changes the relative position of two 1

When the sequence is ordered, the fast row is degraded to bubble sort

Sorting algorithm collation (Python version)

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.