python 九大排序

1,冒泡排序

def bubbleSort(arr):
    for i in range(1, len(arr)):
        for j in range(0, len(arr) - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr


if __name__ == '__main__':
    arr = [34, 6, 3, 6, 56, 24, 12, 2]
    set = bubbleSort(arr)
    print(set)

2选择排序

def selectedSort(myList):
lenth = len(myList)
for i in range(0, lenth):
smallest = i
for j in range(i + 1, lenth):
if myList[j] < myList[smallest]:
tmp = myList[smallest]
myList[smallest] = myList[j]
myList[j] = tmp
print("smallest:", myList[smallest])
print(myList)

if __name__=='__main__':
myList = [5, 3, 56, 2, 45, 9, 4, 76, 23]

print('selectedSort:')
selectedSort(myList)

 3,插入排序

def insertionSort(myList):
for i in range(1, len(myList)):
key = myList[i]
j = i - 1
while j >= 0 and myList[j] > key:
myList[j + 1] = myList[j]
j -= 1
myList[j + 1] = key
return myList


if __name__ == '__main__':
myList = [48, 2, 9, 1, 5, 56, 34, 87]
set=insertionSort(myList)
print(set)

4,快速排序

def quick_sort(array, left, right):
    if left >= right:
        return
    low = left
    high = right
    key = array[low]

    while low < high:
        while low < high and array[high] > key:
            high -= 1
        array[low] = array[high]
        array[high] = key

        while low < high and array[low] <= key:
            low += 1
        array[high] = array[low]
        array[low] = key

    quick_sort(array, left, low - 1)
    quick_sort(array, low + 1, right)


if __name__ == '__main__':
    array = [2, 4, 6, 3, 5, 34, 56, 23, 76, 34, 12, 26, 38]
    print("before sort:", array)
    quick_sort(array, 0, len(array) - 1)
    print("---------")
    print(array)

5堆排序

import time, random


def shift_down(arr, node, end):
    root = node
    # print (root,2*root+1,end)
    while True:     #从root开始对最大堆调整
        child = 2 * root + 1
        if child > end:
            break
        # print("v:", root, arr[root], child, arr[child])
        # print(arr)
        #找出两个child中较大一个
        if child + 1 <= end and arr[child] < arr[child + 1]:  #如果左边小于右边
            child += 1  #设置右边为大

        if arr[root] < arr[child]:
            # 最大堆小于较大child 交换顺序
            tmp = arr[root]
            arr[root] = arr[child]
            arr[child] = tmp

            # 正在调整的节点设置为root
            root = child

        else:
            # 无需调整的时候退出
            break
    # print('----------------')


def heap_sort(arr):  # 堆分类
    # 从最后一个有子节点的孩子开始调整最大堆
    first = len(arr)
    for i in range(first, -1, -1): #(起始,结束,跳转)
        shift_down(arr, i, len(arr) - 1)
    # print('----------end------------', arr)
    # 将最大的放到堆的最后一个,堆-1,继续调整
    for end in range(len(arr) - 1, 0, -1):
        arr[0], arr[end] = arr[end], arr[0]
        shift_down(arr, 0, end - 1)


def main():
    array = [23, 4, 6, 53, 15, 36, 47, 89, 23, 8, 35]
    # print(array)
    # start_t = time.time()
    heap_sort(array)
    # end_t = time.time()
    # print("cost:", end_t - start_t)
    print(array)


if __name__ == '__main__':
    main()

6,归并排序

def mergeSort(arr):
    import math
    if (len(arr)<2):
        return arr
    middle=math.floor(len(arr)/2)
    left,right=arr[0:middle],arr[middle:]
    return meger(mergeSort(left),mergeSort(right))

def meger(left,right):
    result=[]
    while left and right:
        if left[0] <= right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    while left:
        result.append(left.pop(0))
    while right:
        result.append(right.pop(0))
    return result
if __name__=='__main__':
    arr=[3,5,56,23,13,34,59,64,57,53,12]
    ret=mergeSort(arr)
    print(ret)

7,希尔排序

import time, random


def shellSort(source):

    step = int(len(source) / 2)  # 分组步长

    t_start = time.time()

    while step > 0:
        for index in range(0, len(source)):
            if index + step < len(source):
                current_val = source[index]  # 先记下来每次大循环走到的第几个循环的值
                if current_val > source[index + step]:
                    source[index], source[index + step] = source[index + step], source[index]
        step = int(step / 2)

    else:  # 把基本拍好的数据在进行一次插入排序
        for index in range(1, len(source)):
            current_val = source[index]  # 先记下来每次大循环走到的第几个循环的值
            position = index

            # 当前元素的左边的紧靠的元素比它大,要把左边的元素一个一个的往右移一位,给当前这个值插入到左边挪一个位置出来
            while position > 0 and source[position - 1] > current_val:
                source[position] = source[position - 1]  # 把左边元素向右移一位
                position -= 1  # 只一次左移只能把当前元素一个位置 ,还得继续左移只到此元素放到排序好的列表的适当位置 为止
            source[position] = current_val  # 已经找到了左边排序好的列表里不小于current_val的元素的位置,把current_val放在这里
    
    t_end = time.time() - t_start
    print("cost:", t_end)
    return (source)


if __name__ == '__main__':
    source = [54, 56, 2, 6, 8, 34, 76, 23, 11, 45, 32]
    # source = [random.randrange(10000 + i) for i in range(10000)]
    ret = shellSort(source)
    print(ret)

8,计数排序

def countingSort(arr,maxValue):
    bucketLen=maxValue+1
    bucket=[0]*bucketLen
    sortedIndex=0
    arrLen=len(arr)
    for i in range(arrLen):
        if not bucket[arr[i]]:
            bucket[arr[i]]=0
        bucket[arr[i]] += 1
    for j in range(bucketLen):
        while bucket[j]>0:
            arr[sortedIndex]=j
            sortedIndex +=1
            bucket[j] -= 1
    return arr


if __name__=='__main__':
    arr=[45,7,23,7,45,2,7,23,43,49,27,34,25,14,9,3]
    ret=countingSort(arr,49)
    print(ret)

9,基数排序

def radixSort(arr):
    i = 0                 #初始为个位排序
    n = 1                 #最小的位数置为1(包含0)
    max_num = max(arr)     #待排序数组中最大数
    while max_num > 10**n:  
        n += 1
    while i < n:
        bucket = {}                 #用字典构建桶
        for x in range(10):
            bucket.setdefault(x, [])    #将每个桶置空
        for x in arr:                        #对每一位进行排序
            radix =int((x / (10**i)) % 10)   #得到每位的基数
            bucket[radix].append(x) #将对应的数组元素加入到相应位基数的桶中
        j = 0
        for k in range(10):
            if len(bucket[k]) != 0:     #若桶不为空
                for y in bucket[k]:     #将该桶中每个元素
                    arr[j] = y       #放回到数组中
                    j += 1
        i += 1

if __name__ == '__main__':
    arr = [12,3,45,3543,214,1,4553]
    radixSort(arr)
    print(arr)

 

 

转载于:https://www.cnblogs.com/lang185/p/11380595.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值