Python sorting algorithm

Source: Internet
Author: User

1. Bubble method (Direct exchange Element)

1 defBubble_sort (a_list):2A_len = Len (a_list)-13      whileA_len >0:4          forIinchRange (A_len):5             ifA_list[i] >a_list[i+1]:6A_LIST[I],A_LIST[I+1] = a_list[i+1],a_list[i]7 8A_len-=19 Ten if __name__=='__main__': Onea_list=[20,40,30,90,50,80,70,60,110,100] A Bubble_sort (a_list) -     Print(a_list)

2, select the sorting method (swap element position in the table, select the largest after Exchange elements)

1 defSelection_sort (a_list):2Alen =Len (a_list)3      whileAlen >0:4Postion =05          forIinchRange (1, Alen):6             ifA_list[i] >A_list[postion]:7Postion = i#Select the maximum element position subscript8A_list[postion],a_list[alen-1] = a_list[alen-1],a_list[postion]9Alen-= 1Ten  One if __name__=='__main__': Aa_list=[20,40,30,90,50,80,70,60,110,100] - Selection_sort (a_list) -     Print(a_list)

3. Insert sorting to insert the data into the sorted sequence. A stable sorting method.

1 defInsert_sort (alist):2Length =Len (alist)3      forIndexinchRange (1, length):4p =Index5          whilep >0:6             ifALIST[P] < Alist[p-1]:7ALIST[P],ALIST[P-1] = alist[p-1],alist[p]8P-= 19     returnAlist

Python sorting algorithm

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.