python实现排序算法

算法设计与分析的作业,使用python实现,简单记录一下

冒泡排序 BubbleSort

#从小到大排序
def BubbleSort(waitsortlist):
    for i in range(0,len(waitsortlist)-1):
        for j in range(0,len(waitsortlist)-1-i):
            if waitsortlist[j+1]<waitsortlist[j]:
                waitsortlist[j+1],waitsortlist[j]=waitsortlist[j],waitsortlist[j+1]

选择排序 SelectionSort

def SelectionSort(waitsortlist):
    for i in range(0,len(waitsortlist)-1):
        min=i
        for j in range(i+1,len(waitsortlist)):
            if waitsortlist[j]<waitsortlist[min]:
                min=j
        waitsortlist[i],waitsortlist[min]=waitsortlist[min],waitsortlist[i]

验证上面两个算法正确性:

def main():
    waitsortlist=[2,1,6,5,8,9,4]
    SelectionSort(waitsortlist)
    # BubbleSort(waitsortlist)
    print(waitsortlist)

快速排序 QuickSort

def QuickSort(waitsortlist,left,right):
    if left>right:
        return
    left_index,right_index=left,right
    temp=waitsortlist[left]
    while left_index!=right_index:
        while left_index<right_index and waitsortlist[right_index]>=temp:
            right_index-=1
        while left_index<right_index and waitsortlist[left_index]<=temp:
            left_index+=1
        if left_index<right_index:
            waitsortlist[left_index],waitsortlist[right_index]=waitsortlist[right_index],waitsortlist[left_index]
    waitsortlist[left],waitsortlist[left_index]=waitsortlist[left_index],waitsortlist[left]
    QuickSort(waitsortlist,left,left_index-1)
    QuickSort(waitsortlist,left_index+1,right)

归并排序 MergeSort

def merge(waitsortlist,left,might,right):
    left_index,right_index=left,might+1
    temp=[]
    while left_index<=might and right_index<=right:
        if waitsortlist[left_index]<waitsortlist[right_index]:
            temp.append(waitsortlist[left_index])
            left_index+=1
        else:
            temp.append(waitsortlist[right_index])
            right_index+=1
    while left_index<=might:
        temp.append(waitsortlist[left_index])
        left_index+=1
    while right_index<=right:
        temp.append(waitsortlist[right_index])
        right_index+=1
    t=0
    while left<=right:
        waitsortlist[left]=temp[t]
        left+=1
        t+=1


#分 治
def mergeSort(waitsortlist,left,right):
    if left<right:
        might=int((left+right-1)/2)
        mergeSort(waitsortlist,left,might)
        mergeSort(waitsortlist,might+1,right)
        merge(waitsortlist,left,might,right)

验证上面两个算法正确性:

def main():
    waitsortlist = [2, 1, 6, 5, 8, 9, 4]
    QuickSort(waitsortlist,0,len(waitsortlist)-1)
    print(waitsortlist)
    waitsortlist = [2, 1, 6, 5, 8, 9, 4]
    mergeSort(waitsortlist, 0, len(waitsortlist) - 1)
    print(waitsortlist)
    return

Over

posted @ 2020-11-24 15:38  春告鳥  阅读(155)  评论(0编辑  收藏  举报