zoukankan      html  css  js  c++  java
  • python 冒泡排序

    冒泡排序:

    相邻的两个数字先进行比较,也就是li[0]和li[1]进行比较,如果不是大于的关系,就继续依次进行li[1]和li[2]比较,进行交换然后每一次扫描得到的新列表如下:

    li = [11,22,32,344,3,]      
    for i in range(len(li)-1):      
        xin = (li[i])          
        kai = li[i+1]             
        if li[i] >li[i+1]:
            temp = li[i]
            li[i] = li[i+1]
            li[i+1]=temp
    print(li)
    for i in range(len(li)-2):
        xin = (li[i])
        kai = li[i+1]
        if li[i] >li[i+1]:
            temp = li[i]
            li[i] = li[i+1]
            li[i+1]=temp
    print(li)
    for i in range(len(li)-3):
        xin = (li[i])
        kai = li[i+1]
        if li[i] >li[i+1]:
            temp = li[i]
            li[i] = li[i+1]
            li[i+1]=temp
    print(li)
    for i in range(len(li)-3):
        xin = (li[i])
        kai = li[i+1]
        if li[i] >li[i+1]:
            temp = li[i]
            li[i] = li[i+1]
            li[i+1]=temp
    print(li)
    执行结果:
    [11, 22, 32, 3, 344]
    [11, 22, 3, 32, 344]
    [11, 3, 22, 32, 344]
    [3, 11, 22, 32, 344]
    
    冒泡排序
    for j in range(len(li)): #j:1,2,3
        for i in range(len(li)-1):
            if li[i] >li[i+1]:
                temp = li[i]
                li[i] = li[i+1]
                li[i+1]=temp
    print(li)
    
    执行结果
    [3, 11, 22, 32, 344]
    
  • 相关阅读:
    WEB环境安装步骤v1.2
    将m3u8格式转成mp4格式
    MySQL简介及安装v0.1
    使用脚本pull阿里云的k8s镜像并更改标签
    常用脚本
    常用命令
    记录一下环境变量IFS特定场景使用技巧
    hp-unix创建和更改LV
    HP-UNIX常用命令
    Linux集群搭建
  • 原文地址:https://www.cnblogs.com/guokaixin/p/5490181.html
Copyright © 2011-2022 走看看