排序算法总结

常用的排序算法:

  1. Low B三人组:冒泡排序、选择排序、插入排序
  2. N B比三人组:快速排序、堆排序、归并排序
  3. 其他排序:计数排序、希尔排序、基数排序
    冒泡排序
    核心思想:遍历数组
def bubble_sort(List):
    n = len(List)
    for i in range(n - 1):#循环用来控制排序的次数
        exchange = False
        for j in range(n-i-1):#循环用来移动指针
            if List[j] > List[j+1]:
                List[j], List[j+1] = List[j+1], List[j]
                exchange = True
        if not exchange:
            return
    return(List)
#时间复杂度O(N2)

选择排序

def select_sort_simple(List):
    n = len(List)
    res = []
    for _ in range(n):
        min_num = min(List)#min函数一定是O(N),min函数要遍历整个数组
        res.append(min_num)
        List.remove(min_num)#如果列表中有多个相同数,remove函数会从左向右删除;remove函数时间复杂度O(N)
    return(res)
a = [1,1,3,4,2,2,2,1]
print(select_sort_simple(a))

def select_sort(List):
    n = len(List)
    for i in range(n-1):#控制排序的次数
        min_i = i
        for j in range(i+1, n):
            if List[j] < List[min_i]:
                min_i = j

        List[i], List[min_i] = List[min_i], List[i]
    return(List)
a = [1,1,3,4,2,2,2,1]
print(select_sort(a))

插入排序

#时间复杂度O(N2)

def insert_sort(List):
    n = len(List)
    for i in range(1, n):
        tem = List[i]
        j = i - 1
        while j >= 0 and List[j] > tem:#注意这里不能吧tem写成 List[i],因为在向右移动时, List[i]变了
            List[j+1] = List[j]
            j-=1
        List[j+1] = tem
    return(List)
a = [1,1,3,4,2,2,2,1]
print(insert_sort(a))      

快速排序
时间复杂度O(NlogN)

def partition(List, left, right):
    tem = List[left]#先选择一个数作为中间值,这里选择最左边的
    while left < right:#
        while left < right and List[right] >= tem:#当右边的数大于tem时,向左移动右指针,直到小于tem;由于了可能会出现一直移动到right小于left,这时right为负数,所以加上left < right
            right-=1
        List[left] = List[right]#当找到right小于left时,把right赋值给left,这时right为空(也不是真的为空,只不过赋值给left,所以得找一个属赋值给他
        while left < right and List[left] <= tem:#当右边交换后,由于right为空,所以从左边找比tem大的然后赋值给right,这样就可以保证右边始终大于左边
            left+=1
        List[right] = List[left]
    List[left] = tem#最后left=right,把开始的tem,也就是中间值赋值给left
    return(left)
a = [5,7,4,6,3,1,2,9,8]
print(partition(a, 0, len(a) - 1))

def quick_sort(List, left, right):
    if left < right:
        mid = partition(List, left, right)
        quick_sort(List, left, mid - 1)
        quick_sort(List, mid+1, right)
    return(List)
a = [5,7,4,6,3,1,2,9,8]
print(quick_sort(a, 0, len(a) - 1))

你可能感兴趣的:(leetcode-python)