快排,堆排

快排时间复杂度一般O(nlogn)最坏是O(n方),python中sort方法默认为归并排序,使用C编写的,速度更快;

快排要注意递归深度

import sys
sys.setrecursionlimit(n)  #设置递归深度n
print(sys.getrecursionlimit())  #获取默认递归深度

快1:

def s(val,left,right):
    
    if left < right:
        mid = par(val,left,right)
        s(val,left,mid-1)
        s(val,mid+1,right)
        
def par(val,left,right):
    
    tmp = val[left]
    while left < right:
        while left < right and tmp <= val[right]:
            right -= 1
        val[left] = val[right]
        while left < right and tmp >= val[left]:
            left += 1
        val[right] = val[left]
    val[left] = tmp
    
    return left

def sort(val):
    s(val,0,len(lst)-1)
    
lst = [6,5,4,1,3,2]
sort(lst)
print(lst)

快2:

def qSort(lst):
   quickSort(lst,0,len(lst)-1)
   
def quickSort(lst,first,last):
    
   if first<last:
       splitpoint = partition(lst,first,last)
       quickSort(lst,first,splitpoint-1)
       quickSort(lst,splitpoint+1,last)
       
def partition(lst,first,last):
   pivotvalue = lst[first]
   left = first+1
   right = last
   done = False
   
   while not done:
       while left <= right and lst[left] <= pivotvalue:
           left = left + 1
       while left <= right and lst[right] >= pivotvalue:
           right = right -1
       if left > right:
           done = True
       else:
           temp = lst[left]
           lst[left] = lst[right]
           lst[right] = temp
   temp = lst[first]
   lst[first] = lst[right]
   lst[right] = temp
   
   return right

lst = [54,26,93,17,77,31,44,55,20]
qSort(lst)
print(lst)

 快3:

def q(val):
    if len(val) <= 1:
        return val
    base = val[0]
    left = []
    right = []
    for i in val[1:]:
        left.append(i) if i <= base else right.append(i)
    return q(left) + [base] + q(right)

 堆排:先建堆,后排序。时间复杂度一般O(nlogn)最坏是O(nlogn)

#采用大根堆
def build_heap(val,curr,last):      #curr为当前父节点索引,last最后一个叶节点索引 tmp
= val[curr] j = 2*curr+1 while j <= last: if j < last and val[j] < val[j+1]: j += 1 if val[j] > tmp: val[curr] = val[j] curr = j j = 2 * curr + 1 else: break val[curr] = tmp def heap_sort(val): n = len(val) for i in range((n-2)//2,-1,-1):  #注意此处,当前节点为 i ,其父节点为 (i-1)//2 或 (i+1)//2-1 build_heap(val,i,n-1) for i in range(n): val[0],val[n-1-i] = val[n-1-i],val[0] build_heap(val,0,n-2-i)

渐变 --> 突变
原文地址:https://www.cnblogs.com/lybpy/p/8146679.html