• python实现排序算法


    冒泡排序 
    import random
    def BubbleSort(num):
        n=len(num)
        for i in range(0,n):
            for j in range(i,n):
                if num[i]>=num[j]:
                    num[i],num[j]=num[j],num[i]
        return num
     
    选择排序
    def SelectSort(num):
        for i in range(0,len(num)):
            mindex=i
            for j in range(i,len(num)):
                if num[mindex]>num[j]:
                    mindex=j
            num[mindex],num[i]=num[i],num[mindex]
        return num
     
    插入排序
    def InsertSort(num):
        for i in range(1,len(num)):
            j=i-1
            tmp=num[i]
            while j>0 and tmp<num[j]:
                num[j+1]=num[j]            
                j-=1
            num[j]=tmp
        return num
     
    归并排序
    def MergerSort(num):
        if len(num)<=1:
            return num
        left=MergerSort(num[:len(num)/2])
        right=MergerSort(num[len(num)/2:])
        result=[]
        while len(left)>0 and len(right)>0:
            if left[0]>right[0]:
                result.append(right.pop(0))
            else:
                result.append(left.pop(0))
        if len(left)>0:
            result.extend(MergerSort(left))
        else:
            result.extend(MergerSort(right))
        return result
     
    快速排序
    def QuickSort(num):
        if len(num)<=1:
            return num
        greater=[]
        less=[]
        p=num.pop(random.randint(0,len(num)-1))
        for item in num:
            if item < p:
                less.append(item)
            else:
                greater.append(item)
        return QuickSort(less)+[p]+QuickSort(greater)

  • 相关阅读:
    vim编辑器下nginx.conf语法高亮
    Spring Boot 警告:An illegal reflective access operation has occurred
    Idea使用 MyBatis Generator 插件快速生成代码
    SpringBoot 自定义线程池处理异步任务
    idea 处理mybatis的mapper.xml警告提示信息让其不显示
    mybatis 报文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"
    zookeeper生成分布式自增ID
    Navicat卸载注册表 激活码
    mybatis自定义TypeHandler实现list转string
    Java创建ES索引实现
  • 原文地址:https://www.cnblogs.com/joangaga/p/5763756.html
Copyright © 2020-2023  润新知