• 各种排序算法


    import sys
    
    sys.setrecursionlimit(10000000)###设置最大递归深度
    ## 冒泡算法
    # 时间复杂度:O(n^2) 空间复杂度:O(1)
    def bubble_sort(li):
        for i in range(len(li)-1): # i = 0
            flag = False
            for j in range(len(li)-1-i): # j = 6
                if li[j] > li[j+1]: # li[j] = li[2] = 3 > li[j+1]=li[3]=4
                    li[j], li[j+1] = li[j+1], li[j]
                    flag = True
            if not flag:
                return
    
    ### 选择排序
    ### 时间复杂度: O(n^2) 空间复杂度: O(1)
    def select_sort(li):
        for i in range(len(li)-1):
            minLoc = i
            for j in range(i+1, len(li)):
                if li[minLoc] > li[j]:
                    li[minLoc], li[j] = li[j], li[minLoc]
    
    ### 插入排序
    ### 时间复杂度: O(n^2) 空间复杂度: O(1)
    def insert_sort(li):
        for i in range(1, len(li)):
            tmp = li[i]
            j = i - 1
            while j>=0 and li[j] > tmp:
                li[j+1] = li[j]
                j = j - 1
            li[j+1] = tmp
    
    ### 快速排序
    ### 时间复杂度: O(nlogn)
    def partition(li, left, right):  ### O(n)
        tmp = li[left]
        while left < right:
            while left < right and li[left] <= tmp:
                left = left + 1
            li[right] = li[left]
    
            while left < right and  li[right] >= tmp:
                right = right - 1
            li[left] = li[right]
    
    
    
        li[left] = tmp
        return left
    
    def quick_sort(li, left, right):
        if left < right:
            mid = partition(li, left, right) ### O(n)
            quick_sort(li, left, mid-1)  ### O(logn)
            quick_sort(li, mid+1, right) ### O(logn)
            ### O(logn)
    
    import random, time
    
    li = [random.randint(1,1000) for i in range(100000)]
    # print(li)
    start = time.time()
    quick_sort(li, 0, len(li)-1)
    print('quick_sort: ', time.time() - start)
    
    
    li = [random.randint(1,1000) for i in range(100000)]
    start = time.time()
    bubble_sort(li)
    print('bubble_sort: ', time.time() - start)
    
    li = [random.randint(1,1000) for i in range(100000)]
    start = time.time()
    select_sort(li)
    print('select_sort: ', time.time() - start)
    
    li = [random.randint(1,1000) for i in range(100000)]
    start = time.time()
    insert_sort(li)
    print('insert_sort: ', time.time() - start)
    
    
    
    
    # print(li)
  • 相关阅读:
    Collections接口下的Comparetor类和Comparable接口排序
    MySQL(二)、数据库数据类型
    MySQL(表设置、详细说明查询操作)、JDBC基础
    IO流:对象流、Poperties类
    IO流:System.in、SequenceInputStream合并流、内存输入输出流、数据流
    IO流:文件对象、字符流、字节流、缓冲流
    泛型
    集合
    String常用方法、toString()、equals()、compareTo()
    继承、抽象、接口、封装
  • 原文地址:https://www.cnblogs.com/tangda/p/11116034.html
Copyright © 2020-2023  润新知