码迷,mamicode.com
首页 > 编程语言 > 详细

常见low比排序

时间:2020-01-02 18:43:06      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:else   第一个   val   line   元素   sea   range   冒泡排序   code   

冒泡排序
def maopao(li):
    for i in range(0,len(li)-1):
        for j in range(0,len(li)-i-1):
            if li[j]>li[j+1]:
                li[j],li[j+1] = li[j+1],li[j]

li = [23,645,6,3,65,85,25,756,8]
maopao(li)

print(li)
二分查找法
def erfencha(li,val):
    left = 0
    right = len(li)
    while left <=right:
        mid = (left+right)//2
        if val == li[mid]:
            print('找到了,这个数是第%d个数'%(mid+1))
        if val >li[mid]:
            left = mid +1
        else:
            right = mid-1


li = [1,2,5,645,3453,645656,234245645646]
erfencha(li,2)
顺序查找

顺序查找,也叫线性查找,从列表第一个元素开始,顺序进行搜索,直到找到元素或搜索到列表最后一个元素为止。
时间复杂度:O(n)


def linear_search(li,val):
    for ind,v in enumerate(li):
        if v==val:
            print(ind)
        else:
            print("没找到")
li = [1,3,4,6,4,52,7,3,8]

linear_search(li,6)
选择排序
def select_sort_simple(li):
    for i in range(0,len(li)-1):
        min_log = i
        for j in range(i,len(li)):
            if li[j] <li[min_log]:
                min_log = j
        li[i],li[min_log] = li[min_log],li[i]
        print(li)
li = [234,1,43,6546,4645,2,235,543,62,5,34]

select_sort_simple(li)


>>
[1, 234, 43, 6546, 4645, 2, 235, 543, 62, 5, 34]
[1, 2, 43, 6546, 4645, 234, 235, 543, 62, 5, 34]
[1, 2, 5, 6546, 4645, 234, 235, 543, 62, 43, 34]
[1, 2, 5, 34, 4645, 234, 235, 543, 62, 43, 6546]
[1, 2, 5, 34, 43, 234, 235, 543, 62, 4645, 6546]
[1, 2, 5, 34, 43, 62, 235, 543, 234, 4645, 6546]
[1, 2, 5, 34, 43, 62, 234, 543, 235, 4645, 6546]
[1, 2, 5, 34, 43, 62, 234, 235, 543, 4645, 6546]
[1, 2, 5, 34, 43, 62, 234, 235, 543, 4645, 6546]
[1, 2, 5, 34, 43, 62, 234, 235, 543, 4645, 6546]
插入排序
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-=1
        li[j+1] = tmp
        print(li)
li = [234,1,43,6546,4645,2,235,543,62,5,34]

print(li)
insert_sort(li)
汉诺塔算法
def hanoi(n,a,b,c):
    s = 0
    if n>0:
        hanoi(n-1,a,c,b)
        print("moving from %s to %s"%(a,c))
        hanoi(n-1,b,a,c)
        s+=1
hanoi(2,'A','B','C')
print(2**64)

常见low比排序

标签:else   第一个   val   line   元素   sea   range   冒泡排序   code   

原文地址:https://www.cnblogs.com/yeyeyeyey/p/12126266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!