Python sorting algorithm

Source: Internet
Author: User

(i) Insert sort

Before each loop, the front I bits are always ordered.

1 defInsert_sort (list):2      forIinchRange (len (list)):3Key =List[i]4          forJinchRange (i-1,-1,-1):5             ifKey <List[j]:6LIST[J+1] =List[j]7LIST[J] =Key8     returnList9 PrintInsert_sort ([5,4,3,2,1])

(ii) Bubble sort

Each cycle, compared to the first of the unordered sub list, has a maximum sink/float to the first

def Bubble_sort (list):      for inch Range (len (list)):          for  in range (i+1, Len (list)):            if list[i] > list[j]:                = List[i], LIST[J]  return list

(iii) Quick sorting

Each time the first number is flag, then the left is smaller than he, the right is bigger than him, and then the recursion

def part_sort (list,start,end):
If Start >= end-1:
Return
Flag = List[start]
i = Start
For j in Range (Start+1,end):
If LIST[J] < flag:
i + = 1
If list[i]! = List[j]:
LIST[I],LIST[J] = List[j],list[i]
Else
Pass
List[i],list[start] = List[start],list[i]
return I
def quick_sort (list,start,end):
If start>=end-1:
Return
Flag_index = Part_sort (list,start,end)
Quick_sort (List,start,flag_index)
Quick_sort (List,flag_index+1,end)
Return list

(iv) Heap sequencing

defFixdown (a,k,n):#Heap from top to bottom, starting with KN=n-1 while2*k<=n:j=2*kifJ<n andA[J]&LT;A[J+1]:#Select the bigger one in the left and right child nodes.J+=1ifa[k]<A[j]: a[k],a[j]=A[j],a[k] k=JElse:               Break    defHeapsort (L): N=len (L)-1 forIinchRange (n//2,0,-1): Fixdown (L,i,len (l) ) whileN>1: l[1],l[n]=l[n],l[1] Fixdown (L,1, N) n-=1returnL[1:] L=[-1,26,5,77,1,61,11,59,15,48,19]#the first element is not used, a placeholderres=heapsort (L)Print(RES)

Python sorting algorithm

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.