初学python,排序算法原理总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27361727/article/details/88635077
#冒泡排序
def bunnle_sort(list):
    count = len(list) - 1
    for index  in range(count,0,-1):
        for sub_index in range(index):
            if list[sub_index] > list[sub_index+1]:
                list[sub_index],list[sub_index+1] = list[sub_index+1],list[sub_index]
    return list
list = [5,4,3,1,8]
print(bunnle_sort(list))

#从小到大或从大到小排序
def sorts(list):
    list1 = sorted(list,reverse = False)
    return list1

print(sorts(list))

#快速排序
lists1 = [8,6,9,2,5]
def quike_sort(lists,left,right):
    if left >= right:
        return lists
    #定义游标
    low = left
    high = right
    #定义标志元素K值
    key = lists[low]
    while low < high:
        #从右侧往左依次和标志元素进行对比,如果右侧的元素大于标志元素Key
        while low < high and lists[high] >= key:
            #右侧减一
            high-=1
        #否则low赋上high值
        lists[low] = lists[high]
        # 从左侧往右依次和标志元素进行对比,如果左侧的元素小于标志元素Key
        while low < high and lists[low] <= key:
            # 左侧加一
            low += 1
        # 否则high赋上low值
        lists[high] = lists[low]
    #最后给high位置赋值
    lists[high] = key
    #处理左侧元素
    quike_sort(lists,left,low-1)
    quike_sort(lists,low+1,right)
    return lists

print(quike_sort(lists1,0,4))

#求素数
def is_prime(n):
    if n <=1:
        return False
    for i in range(2,n-1):
        if n % i ==0:
            return False
    return True

for i in range(0,100):
    if is_prime(i):
        print(i)

猜你喜欢

转载自blog.csdn.net/qq_27361727/article/details/88635077