常见low比排序

Posted yeyeyeyey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常见low比排序相关的知识,希望对你有一定的参考价值。

冒泡排序
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比排序的主要内容,如果未能解决你的问题,请参考以下文章

各种排序算法概览

常见排序之归并排序

排序算法

常见排序之快速排序

常见排序算法,待补充树

递归法快速排序