排序

#选择排序:每趟排序选择最小或最大的一个,交换位置

def select_sort(alist):
    n = len(alist)
    for j in range(n-1):
        min = j #记录最小值的索引
        for i in range(j + 1, n):
            if alist[min] > alist[i]:
                min = i
        alist[j], alist[min] = alist[min], alist[j]
        print(alist)
lst = [ 58,23,64,12,9,46,37,21,8]
select_sort(lst)
print(lst)

#希尔排序

def shellSort(alist):
    #选择排序的分治实现
    n = len(alist)
    gap = n // 2

    while gap > 0:
        for j in range(gap,n):
            i = j
            while i > 0:
                if alist[i] < alist[ i - gap]:
                    alist[i], alist[i - gap] = alist[i - gap], alist[i]
                    i -= gap
                else:
                    break
        gap //= 2

lst = [ 64,12,9,46,37,21,8]
shellSort(lst)
print(lst)

#归并排序

def mergeSort(alist):
    n = len(alist)
    if n <= 1:
        return alist
    mid = n // 2
    #分成小块
    left = mergeSort(alist[:mid])
    right =  mergeSort(alist[mid:])
    i, j = 0, 0
    res = [ ]
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            res.append(left[i])
            i += 1
        else:
            res.append(right[j])
            j += 1
    res += left[i:]
    res += right[j:]
    return res


lst = [ 64,12,9,46,37,21,8]
ls =  mergeSort(lst)
print(ls)

#插入排序

def insertSort(alist):
    #默认第一个有序,从后面无序的元素中依次与前面有序序列从后向前比较
    for i in range(1, len(alist)):
        j = i
        while j > 0:
            if alist[j] < alist[j-1]:
                alist[j], alist[j-1] = alist[j-1], alist[j]
                j -= 1
            else:
                break
lst = [ 64,12,9,46,37,21,8]
insertSort(lst)
print(lst)
上一篇:Python数据结构与算法_第4节_栈 & 队列 & 排序与搜索


下一篇:插入排序