mit 6.006 lecture-notes 003

102 阅读1分钟

Permutation Sort:

For each permuatation, check each whether is orded

def permutation_sort(A): 
    for B in permutations(A): #O(n!)
        if is_sorted(B): # O(n)
            return B

Analysis:

You will try all possibilities.(Brute Force)
Running time:O(n!\cdotn)

Selection Sort:

Find a largest number then recursively sort

def prefix_max(A, i):
    if i > 0:
        j = prefix_max(A, i - 1)
        if A[j] > A[i]:  # 数组的最后一位只有两种可能,比前i-1位的最大数还要大or小
            return j  # 换种方式说明,最大数要么是最后一个元素,要么前i-1位的最大数
    return i


def selection_sort(A, i=None):
    if i is None: i = len(A) - 1
    if i > 0:  # 当i=0时,无需再进行排序,函数结束
        j = prefix_max(A, i)
        A[i], A[j] = A[j], A[i]  # 最后一位数与数组最大数进行交换
        selection_sort(A, i - 1)  # 递归处理

Running time:

O(n2)O(n^2),递归了n次,每次循环running time为O(n)O(n)

Merge Sort:

def merge_sort(A, a=0, b=None):
    if b is None: b = len(A)
    if b - a > 1:
        c = (a + b + 1) // 2
        merge_sort(A, a, c)
        merge_sort(A, c, b)
        L, R = A[a:c], A[c:b]
        merge(A, L, R, i, j, a, b)


def merge(A, L, R, i, j, a, b):  # i,j是子数组,a,b是原数组
    if b > a:
        if (j <= 0) or (i > 0 and L[i] > R[j]):
            A[b - 1] = L[i - 1]
            i = i - 1
        else:
            A[b - 1] = R[j - 1]
            j = j - 1
        merge(A, L, R, i, j, a, b - 1)