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)