zoukankan      html  css  js  c++  java
  • 九大常用排序算法 python

    1.冒泡排序

    import random
    from timewrap import *
    @cal_time
    def bubble_sort(li):
        for i in range(len(li)-1):
    
            for j in range(len(li)-i-1):
                if li[j] > li[j+1]:
                    li[j],li[j+1]=li[j+1],li[j]
    
    
    @cal_time
    def bubble_sort_2(li):
        '''改良版'''
        for i in range(len(li)-1):
            flag = False
            for j in range(len(li)-i-1):
                if li[j] > li[j+1]:
                    li[j],li[j+1]=li[j+1],li[j]
                    flag=True
            if not flag:
                return
    
    li = list(range(10000))
    random.shuffle(li)
    # print(li)
    # bubble_sort(li)#12.725000143051147
    bubble_sort_2(li)#12.974000215530396
    print(li)

    2.选择排序

    import random
    
    from timewrap import *
    
    @cal_time
    def select_sort(li):
        '''选择数值最小的数放在前面'''
        for i in range(len(li)-1):
            min_index = i
            for j in range(i+1,len(li)):
                if li[j] < li[min_index]:
                    min_index = j
            li[i],li[min_index] = li[min_index],li[i]
    
    
    li = list(range(10000))
    random.shuffle(li)
    print(li)
    select_sort(li)
    print(li)

    3.插入排序

    import random
    
    from timewrap import *
    
    
    @cal_time
    def insert_sort(li):
        for i in range(1,len(li)):
            tmp = li[i]
            j = i-1
            while li[j] > tmp and j >= 0:
                li[j+1] = li[j]
                j-=1
            li[j+1] = tmp
    
    li = list(range(10000))
    random.shuffle(li)
    print(li)
    insert_sort(li)
    print(li)

    4.快速排序

    import random
    import sys
    
    from 排序算法.timewrap import *
    
    sys.setrecursionlimit(100000)
    
    def partition(li, left, right):
        # ri = random.randint(left, right)
        # li[left], li[ri] = li[ri], li[left]
        tmp = li[left]
        while left < right:
            while left < right and li[right] >= tmp:
                right -= 1
            li[left] = li[right]
            while left < right and li[left] <= tmp:
                left += 1
            li[right] = li[left]
        li[left] = tmp
        return left
    
    
    def _quick_sort(li, left, right):
        if left < right:    # 至少有两个元素
            mid = partition(li, left, right)
            _quick_sort(li, left, mid-1)
            _quick_sort(li, mid+1, right)
    
    @cal_time
    def quick_sort(li):
        return _quick_sort(li, 0, len(li)-1)
    
    @cal_time
    def sys_sort(li):
        li.sort()
    
    li = list(range(10000))
    random.shuffle(li)
    
    
    #sys_sort(li1)
    quick_sort(li)

    5.堆排序

    import random
    
    from 排序算法.timewrap import *
    
    
    def _sift(li, low, high):
        """
        :param li:
        :param low: 堆根节点的位置
        :param high: 堆最有一个节点的位置
        :return:
        """
        i = low  # 父亲的位置
        j = 2 * i + 1  # 孩子的位置
        tmp = li[low]  # 原省长
        while j <= high:
            if j + 1 <= high and li[j + 1] > li[j]:  # 如果右孩子存在并且右孩子更大
                j += 1
            if tmp < li[j]:  # 如果原省长比孩子小
                li[i] = li[j]  # 把孩子向上移动一层
                i = j
                j = 2 * i + 1
            else:
                li[i] = tmp  # 省长放到对应的位置上(干部)
                break
        else:
            li[i] = tmp  # 省长放到对应的位置上(村民/叶子节点)
    
    
    def sift(li, low, high):
        """
        :param li:
        :param low: 堆根节点的位置
        :param high: 堆最有一个节点的位置
        :return:
        """
        i = low         # 父亲的位置
        j = 2 * i + 1   # 孩子的位置
        tmp = li[low]   # 原省长
        while j <= high:
            if j + 1 <= high and li[j+1] > li[j]: # 如果右孩子存在并且右孩子更大
                j += 1
            if tmp < li[j]: # 如果原省长比孩子小
                li[i] = li[j]  # 把孩子向上移动一层
                i = j
                j = 2 * i + 1
            else:
                break
        li[i] = tmp
    
    
    @cal_time
    def heap_sort(li):
        n = len(li)
        # 1. 建堆
        for i in range(n//2-1, -1, -1):
            sift(li, i, n-1)
        # 2. 挨个出数
        for j in range(n-1, -1, -1):    # j表示堆最后一个元素的位置
            li[0], li[j] = li[j], li[0]
            # 堆的大小少了一个元素 (j-1)
            sift(li, 0, j-1)
    
    
    li = list(range(10000))
    random.shuffle(li)
    heap_sort(li)
    print(li)
    
    # li=[2,9,7,8,5,0,1,6,4,3]
    # sift(li, 0, len(li)-1)
    # print(li)

    6.并归排序

    import random
    
    
    def merge(li, low, mid, high):
        i = low
        j = mid + 1
        ltmp = []
        while i <= mid and j <= high:
            if li[i] < li[j]:
                ltmp.append(li[i])
                i += 1
            else:
                ltmp.append(li[j])
                j += 1
        while i <= mid:
            ltmp.append(li[i])
            i += 1
        while j <= high:
            ltmp.append(li[j])
            j += 1
        li[low:high+1] = ltmp
    
    
    def _merge_sort(li, low, high):
        if low < high:  # 至少两个元素
            mid = (low + high) // 2
            _merge_sort(li, low, mid)
            _merge_sort(li, mid+1, high)
            merge(li, low, mid, high)
            print(li[low:high+1])
    
    
    def merge_sort(li):
        return _merge_sort(li, 0, len(li)-1)
    
    
    li = list(range(16))
    random.shuffle(li)
    print(li)
    merge_sort(li)
    
    print(li)

    7.希尔排序

    def insert_sort(li):
        for i in range(1, len(li)):
            # i 表示无序区第一个数
            tmp = li[i] # 摸到的牌
            j = i - 1 # j 指向有序区最后位置
            while li[j] > tmp and j >= 0:
                #循环终止条件: 1. li[j] <= tmp; 2. j == -1
                li[j+1] = li[j]
                j -= 1
            li[j+1] = tmp
    
    def shell_sort(li):
        d = len(li) // 2
        while d > 0:
            for i in range(d, len(li)):
                tmp = li[i]
                j = i - d
                while li[j] > tmp and j >= 0:
                    li[j+d] = li[j]
                    j -= d
                li[j+d] = tmp
            d = d >> 1

    8.内置堆模块排序

    import heapq, random
    
    li = [5,8,7,6,1,4,9,3,2]
    
    heapq.heapify(li)
    print(heapq.heappop(li))
    print(heapq.heappop(li))
    
    def heap_sort(li):
        heapq.heapify(li)
        n = len(li)
        new_li = []
        for i in range(n):
            new_li.append(heapq.heappop(li))
        return new_li
    
    li = list(range(10000))
    random.shuffle(li)
    # li = heap_sort(li)
    # print(li)
    
    print(heapq.nlargest(100, li))

    9.计数排序

    # 0 0 1 1 2 4 3 3 1 4 5 5
    import random
    import copy
    from timewrap import *
    
    @cal_time
    def count_sort(li, max_num = 100):
        count = [0 for i in range(max_num+1)]
        for num in li:
            count[num]+=1
        li.clear()
        for i, val in enumerate(count):
            for _ in range(val):
                li.append(i)
    
    @cal_time
    def sys_sort(li):
        li.sort()
    
    li = [random.randint(0,100) for i in range(100000)]
    li1 = copy.deepcopy(li)
    count_sort(li)
    sys_sort(li1)
    print(li)
  • 相关阅读:
    字符串转日期
    arcgis server 10.1 PublishingTools工具无法启动Service's containing process has crashed
    net中捕获摄像头视频的方式及对比
    sql server下划线查询
    字符串与图片的Base64编码转换操作
    自定义DataSet
    判断窗体是否已存在实例
    字符串二次处理,补位+截取
    vue踩坑-This relative module was not found
    ajax和axios请求本地json数据对比
  • 原文地址:https://www.cnblogs.com/ldq1996/p/8406894.html
Copyright © 2011-2022 走看看