Python实现一些常用排序算法

摘要:
一些常见的排序#system内置排序算法#list。sort()#heapq模块defsys_heap_sort(列表):importheapqheap=[]foriinrange(len(列表)):heapq。heappress(heap,list[i])foriinrange(len(heap)):list[i]=heapq。heapop(heap)#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("
count_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("
get_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)

全部排序算法大杂烩

Python实现一些常用排序算法第1张Python实现一些常用排序算法第2张
__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("
bubble_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("
insert_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("
select_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("
quckly_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("
heap_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("
megre_sort:")
    return _megre_sort(list,0,len(list)-1)


#-------------------希尔排序-----------------------#
@time_cost
def shell_sort(list):
    print("
shell_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("
count_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("
get_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

免责声明:文章转载自《Python实现一些常用排序算法》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇WPF转换器之通用转换器Linux常用命令及示例(全)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

【python】获取高德地图省市区县列表

项目中需要用省市区来进行检索,原想高德地图肯定会有API来获得这些数据,结果没有找到,有一个接口好像可以用,但是会附带大量的边界坐标点。 所以就不如自己把高德的省市区列表扒下来,自己写接口来完成这个功能。 看到高德地图的js的demo里面有这样的展示页面:http://lbs.amap.com/api/javascript-api/example/u/20...

python-上传文件的几种方式

from requests_toolbelt import MultipartEncoder import requests # from_data上传文件,注意参数名propertyMessageXml data = MultipartEncoder(fields={'propertyMessageXml': ('filename', open('D:...

3、Python字符编码区分utf-8和utf-8-sig

Python 读取文件首行多了"ufeff"字符串 python读取B.txt文件时,控制台打印首行正常,但是若是用首行内容打开文本的话,就会报错: Traceback (most recent call last): A File "E:/python project/multiProcess/test.py", line 32, in <mo...

python合并表

1 import xlrd, xlwt 2 3 # 读取 4 rbook = xlrd.open_workbook('提取+病例合并.xlsx') # 打开文件 5 print("表1:") 6 sheet = rbook.sheet_by_index(0) # 打开对应的表 7 nrow = sheet.nrows...

python 快速触发adb 命令, 快速点击

import subprocess import time # 按照次数来点击它 def loop_click_for_android(run_num=30): res = subprocess.Popen('adb devices', shell=True, stdout=subproce...

使用python asyncio+aiohttp做接口测试(TODO)

线程是操作系统层面的“并行”, 协程是应用程序层面的“并行”。 协程本质上就是:提供一个环境,保存一些需要等待的任务,当这些任务可以执行(等待结束)的时候,能够执行。再等待的过程中,程序可以执行别的任务。 asyncio是python3.4版本引入到标准库因此要注意python版本 我的python环境 Python 3.6.5 (v3.6.5:f59c0...