排序算法小结(python 实现)

1 直接插入排序

#每次将一个待排元素按照其大小排到合适的位置
def insertsort(value):
    n = len(value)
    for i in range(1,n):
        temp = value[i]
        #print(temp)
        j = i-1
        while j >= 0 and temp < value[j]:
            value[j+1] = value[j]
            j -= 1
        value[j+1] = temp
    return value
print(insertsort(l))

2 冒泡排序

#每趟比较出最大的放最后
def bubblesort(value):
    n = len(value)
    flag = 0
    for i in range(n):
        for j in range(n-i-1):
            if value[j] > value[j+1]:
                value[j+1], value[j] = value[j], value[j+1]
                flag = 1
        if flag == 0:
            break
    return value
print(bubblesort(l))

3 快速排序

#每次将轴放到合适的位置
def quicksort(value,l,r):
    i,j = l,r
    if l<r:
        temp = value[l]
        while i != j:
            while i<j and value[j]>temp:
                j -= 1
            if i<j:
                value[i] = value[j]
                i += 1
            while i<j and value[i]<temp:
                i += 1
            if i<j:
                value[j] = value[i]
                j -= 1
        value[i] = temp
        quicksort(value,l,i-1)
        quicksort(value,i+1,r)

quicksort(l,0,len(l)-1)
print(l)

4 选择排序

#每次选最小的
def selectsort(value):
    l = len(value)
    for i in range(l):
        temp = value[i]
        k = i
        for j in range(i+1,l):
            if value[j]<temp:
                temp = value[j]
                k = j
        value[k] = value[i]
        value[i] = temp
    return value
print(selectsort(l))

5 堆排序

#建堆,注意下标
def adjust_heap(value,i,n):
    l = 2*i
    r = 2*i+1
    max = i
    if l<=n:
        if value[l]>value[i]:
            max = l
        if r<=n and value[r]>value[max]:
            max = r
        if max != i:
            value[max],value[i] = value[i],value[max]
            adjust_heap(value,max,n)

def heap_sort(value):
    n = len(value)-1
    for i in range(n/2,0,-1):
        adjust_heap(value,i,n)
    for j in range(n,1,-1):
        value[1],value[j] = value[j],value[1]
        adjust_heap(value,1,j-1)
    return value
print(heap_sort(l))
点赞