排序算法-python

    xiaoxiao2025-03-25  33

    选择排序

    def Sord_select(a): length=len(a) for i in range(length): pos = i for j in range(i+1,length): if a[pos]>a[j]: pos=j if pos!=i: a[pos],a[i]=a[i],a[pos] return a import random a=list(random.randint(1,1000) for i in range(10)) print(a) print(Sord_select(a))

    插入排序

    def insert_sort(a): length=len(a) for i in range(1,length): pos=i-1 w=a[i] while pos>=0 and w<a[pos]: a[pos+1]=a[pos] pos-=1 a[pos+1]=w print(a) return a import random a=list([random.randint(0,100) for i in range(10)]) print(a) print(insert_sort(a))

    希尔排序

    def shell_sort(a): length=len(a) k=length//2 while k: for i in range(k,length): pos = i-k w=a[i] while pos>=0 and w<a[pos]: a[pos+k]=a[pos] pos-=k a[pos+k]=w k//=2 return a import random a=list([random.randint(10,1000) for i in range(10)]) print(a) print(shell_sort(a))

    归并排序

    def merga(L,R): a=[] len_L=0 len_R=0 while len_L<len(L) and len_R<len(R): if L[len_L]>R[len_R]: a.append(R[len_R]) len_R+=1 else: a.append(L[len_L]) len_L+=1 a.extend(L[len_L:]) a.extend(R[len_R:]) return a def merge_sort(a): length=len(a) if length<2: return a Left=a[0:length//2] Right=a[length//2:] return merga(merge_sort(Left),merge_sort(Right)) import random a=list([random.randint(10,1000) for i in range(10)]) print(a) print(merge_sort(a))

    快速排序

    def partition(a,s,t): i=s j=t w=a[i] while i<j: while i<j and a[j]>=w: j-=1 a[i]=a[j] while i<j and a[i]<=w: i+=1 a[j]=a[i] a[i]=w return i def quick_sort(a,s,t): if s<t: i=partition(a,s,t) quick_sort(a,s,i-1) quick_sort(a,i+1,t) import random a=list([random.randint(1,100) for i in range(10)]) print(a) quick_sort(a,0,len(a)-1) print(a)
    最新回复(0)