Python实现一些常用排序算法

一些常用的排序

#系统内置排序算法
#list.sort()
#heapq模块

def sys_heap_sort(list):
    import heapq
    heap = []
    for i in range(len(list)):
        heapq.heappush(heap,list[i])
    for i in range(len(heap)):
        list[i] = heapq.heappop(heap)

 

#python操作列表的方法,它们的时间复杂度

#insert() --->  O(n)

#remove()  ---> O(n)

#append()  -----> O(1)

#in    ------>  0(n)


#计数排序
#规定无序列表元素要求有范围
#统计个元素出现次数,最后修改列表
#对于年龄列表做大规模排序非常试用

def count_sort(list,maxNum):
    print("\ncount_sort:")
    counter = [0 for i in range(maxNum+1)]
    for i in list:
        counter[i] += 1
    i = 0
    for num,c in enumerate(counter):
        for j in range(c):
            list[i] = num
            i += 1

 


#找前n个大数
#方法一:
#时间复杂度O(n^2)
#将无序列表使用排序算法排序,取最后n个互异的数
#方法二:
#时间复杂度O(kn)
#构造一个n个大小的列表,对这个列表使用插入排序,每次从无序列表获取一个元素,插入构造列表,淘汰构造列表最小数,直到无序列表取完
#方法三:
#时间复杂度O(nlogk)
#将前n个数构造一个小根堆,每次从无序列表取一个元素和堆顶元素比较,小则淘汰,大则替换,然后调整堆,直至无序列表取完
#方法四:
#与方法三原理相同,只不过是使用系统heapq模块

#方法二

def topk_search(list,k):
    ltmp = list[0: k + 1]
    insert_sort(ltmp)
    ltmp.reverse()
    print("get_topk:")
    for i in range(k + 1,len(list)):
        j = k - 1
        while j >= 0 and ltmp[j] < list[i]:
            ltmp[j + 1] = ltmp[j]
            j -= 1
        ltmp[j + 1] = list[i]
    return ltmp[0: k]

 

#方法三:

def sift_small(list,low,high):
    i = low
    j = 2 * i + 1
    temp = list[i]
    while j <= high:
        if j < high and list[j] > list[j+1]:
            j += 1
        if temp > list[j]:
            list[i] = list[j]
            i = j
            j = 2 * i + 1
        else:
            break
    list[i] = temp
    list[low],list[high] = list[low],list[high]

def topn_search(list,n):
    print("\nget_topn:")
    heap = list[0:n]
    for i in range(n//2-1,-1,-1):
        sift_small(heap, i, n - 1)
    for i in range(n,len(list)):
        if heap[0] < list[i]:
            heap[0] = list[i]
            sift_small(heap, 0, n - 1)
    for i in range(n-1, -1, -1):
        heap[0],heap[i] = heap[i],heap[0]
        sift_small(heap, 0, i - 1)
    return heap

 

#方法四:

def sys_topn_search(list,n):
    import heapq
    return heapq.nlargest(n,list)

 

 

全部排序算法大杂烩

__author__ = 'cq'


import time
import random
import sys
import copy

def time_cost(func):
    def wrapper(*args,**kwargs):
        sTime = time.time()
        func(*args,**kwargs)
        print("Time cost:%s"%(time.time()-sTime))
        print(args[0])
    return wrapper

#-------------------系统自带排序-----------------------#
@time_cost
def sys_sort(list):
    list.sort()


#-------------------冒泡排序-----------------------#
@time_cost
def bubble_sort(list):
    print("\nbubble_sort:")
    for i in range(len(list)-1):
        tag = 0
        for j in range(len(list)-i-1):
            if list[j] > list[j+1]:
                list[j],list[j+1] = list[j+1],list[j]
                tag = 1
        if not tag:
            return

#-------------------插入排序-----------------------#
@time_cost
def insert_sort(list):
    print("\ninsert_sort:")
    for i in range(len(list)):
        tag = 0
        for j in range(i,0,-1):
            if list[j] < list[j-1]:
                list[j],list[j-1] = list[j-1],list[j]
                tag = 1
            if not tag:
                break

#-------------------选择排序-----------------------#
@time_cost
def select_sort(list):
    print("\nselect_sort:")
    for i in range(len(list)-1):
        min = i
        for j in range(i+1,len(list)):
            if list[min] > list[j]:
                min = j
        if min != i:
            list[i],list[min] = list[min],list[i]

#-------------------快速排序-----------------------#
def part_sort(list,left,right):
    temp = list[left]
    while left < right:
        while left < right and temp <= list[right]:
            right -= 1
        list[left] = list[right]
        while left < right and temp >= list[left]:
            left += 1
        list[right] = list[left]
    list[left] = temp
    return left


def _quckly_sort(list,left,right):
    if left < right:
        mid = part_sort(list,left,right)
        _quckly_sort(list,left,mid-1)
        _quckly_sort(list,mid+1,right)

@time_cost
def quckly_sort(list):
    print("\nquckly_sort:")
    return _quckly_sort(list,0,len(list)-1)

#-------------------堆排序-----------------------#
def sift(list,low,high):
    i = low
    j = 2 * i + 1
    temp = list[i]
    while j <= high:
        if j < high and list[j] < list[j+1]:
            j += 1
        if temp < list[j]:
            list[i] = list[j]
            i = j
            j = 2 * i + 1
        else:
            break
    list[i] = temp
    list[low],list[high] = list[low],list[high]



@time_cost
def heap_sort(list):
    print("\nheap_sort:")
    n = len(list)
    for i in range(n // 2 - 1, -1, -1):
        sift(list, i, n - 1)
    for i in range(n-1, -1, -1):
        list[0],list[i] = list[i],list[0]
        sift(list, 0, i - 1)


#-------------------系统自带堆排序------------------#
@time_cost
def sys_heap_sort(list):
    import heapq
    heap = []
    for i in range(len(list)):
        heapq.heappush(heap,list[i])
    for i in range(len(heap)):
        list[i] = heapq.heappop(heap)



#-------------------归并排序-----------------------#
def ont_megre_sort(list,low,mid,high):
    i = low
    j = mid + 1
    ltmp = []
    while i <= mid and j <= high:
        if list[i] < list[j]:
            ltmp.append(list[i])
            i += 1
        else:
            ltmp.append(list[j])
            j += 1
    while i <= mid:
        ltmp.append(list[i])
        i += 1
    while j <= high:
        ltmp.append(list[j])
        j += 1
    list[low:high+1] = ltmp


def _megre_sort(list,low,high):
    if low < high:
        mid = (low+high)//2
        _megre_sort(list,low,mid)
        _megre_sort(list,mid+1,high)
        ont_megre_sort(list,low,mid,high)

@time_cost
def megre_sort(list):
    print("\nmegre_sort:")
    return _megre_sort(list,0,len(list)-1)


#-------------------希尔排序-----------------------#
@time_cost
def shell_sort(list):
    print("\nshell_sort:")
    gap = len(list) // 2
    while gap > 0:
        for i in range(gap,len(list)):
            temp = list[i]
            j = i - gap
            while j >= 0 and temp < list[j]:
                list[j + gap] = list[j]
                j -= gap
            list[j + gap] = temp
        gap //= 2


#-------------------统计排序-----------------------#
@time_cost
def count_sort(list,maxNum):
    print("\ncount_sort:")
    counter = [0 for i in range(maxNum+1)]
    for i in list:
        counter[i] += 1
    i = 0
    for num,c in enumerate(counter):
        for j in range(c):
            list[i] = num
            i += 1



#-------------------插入排序获取Top前n的数-----------------------#
def topk_search(list,k):
    ltmp = list[0: k + 1]
    insert_sort(ltmp)
    ltmp.reverse()
    print("get_topk:")
    for i in range(k + 1,len(list)):
        j = k - 1
        while j >= 0 and ltmp[j] < list[i]:
            ltmp[j + 1] = ltmp[j]
            j -= 1
        ltmp[j + 1] = list[i]
    return ltmp[0: k]

#-------------------堆排序获取Top前n的数-----------------------#

def sift_small(list,low,high):
    i = low
    j = 2 * i + 1
    temp = list[i]
    while j <= high:
        if j < high and list[j] > list[j+1]:
            j += 1
        if temp > list[j]:
            list[i] = list[j]
            i = j
            j = 2 * i + 1
        else:
            break
    list[i] = temp
    list[low],list[high] = list[low],list[high]

def topn_search(list,n):
    print("\nget_topn:")
    heap = list[0:n]
    for i in range(n//2-1,-1,-1):
        sift_small(heap, i, n - 1)
    for i in range(n,len(list)):
        if heap[0] < list[i]:
            heap[0] = list[i]
            sift_small(heap, 0, n - 1)
    for i in range(n-1, -1, -1):
        heap[0],heap[i] = heap[i],heap[0]
        sift_small(heap, 0, i - 1)
    return heap

#-------------------系统堆排序获取Top前n的数-----------------------#
# @time_cost
def sys_topn_search(list,n):
    import heapq
    return heapq.nlargest(n,list)











def main():
    #生成列表
    list0 = list(range(100))
    first_name = ["","","","",""]
    second_name = ["","","","",""]
    third_name = ["","","","",""]
    listname = [
        {"id":"1000"+str(i),
         "name":random.choice(first_name)+
                random.choice(second_name)+
                random.choice(third_name),
         "age":random.randint(16,60)
        } for i in range(10)
    ]
    random.shuffle(list0)
    random.shuffle(listname)

    #copy四份打乱后的列表
    list1 = copy.deepcopy(list0)
    list2 = copy.deepcopy(list0)
    list3 = copy.deepcopy(list0)
    list4 = copy.deepcopy(list0)
    list5 = copy.deepcopy(list0)
    list6 = copy.deepcopy(list0)
    list7 = copy.deepcopy(list0)
    list8 = copy.deepcopy(list0)
    list9 = copy.deepcopy(list0)
    list10 = copy.deepcopy(list0)
    list11 = copy.deepcopy(list0)
    list12 = copy.deepcopy(list0)

    #设置递归深度
    sys.setrecursionlimit(10000)


    print("sort_list:")
    print(list0)

    # 排序算法
    sys_sort(list0)
    bubble_sort(list1)
    select_sort(list2)
    insert_sort(list3)
    quckly_sort(list4)
    heap_sort(list5)
    sys_heap_sort(list11)
    megre_sort(list6)
    shell_sort(list7)
    count_sort(list8,1000)
    print(topk_search(list9,10))
    print(topn_search(list10,10))
    print(sys_topn_search(list12,10))


if "__main__" == __name__:
    main()
View Code

 

posted @ 2017-12-19 10:38  前路~  阅读(329)  评论(0编辑  收藏  举报