排序算法

十大经典排序算法

# 冒泡排序
def sort(arr):
    le = len(arr)
    for i in range(le-1):
        for j in range(le-1-i):
            if arr[j] > arr[j+1]:
                mid = arr[j+1]
                arr[j+1] = arr[j]
                arr[j] = mid
    return arr

# 选择排序 查找最小值
def sort1(arr):
    le = len(arr)
    min = 0
    for i in range(le):
        min = i
        for j in range(i+1,le):
            if(arr[j]<arr[min]):
                min = j
        wap = arr[i]
        arr[i] = arr[min]
        arr[min] = wap
    return arr
    
# 插入排序
def sort2(arr):
    le = len(arr)
    if le <= 1:
        return arr
    preIndex = 0
    current = 0
    for i in range(1 , le):
        preIndex = i - 1
        current = arr[i]
        while preIndex >= 0 and current < arr[preIndex]:
            arr[preIndex + 1] = arr[preIndex]
            preIndex = preIndex - 1
        arr[preIndex + 1] = current
    return arr


# 希尔排序
def ShellSort(arr):
    le = len(arr)
    temp = le // 2
    gap = le // 2
    while(gap > 0):
        for i in range(0,le):
            temp = arr[i]
            preIndex = i - gap
            while(preIndex >= 0 and arr[preIndex] > temp):
                arr[preIndex + gap] = arr[preIndex]
                preIndex -= gap
            arr[preIndex + gap] = temp
        gap //= 2
    return arr

# 归并排序
def mergeSort(arr):
    if len(arr) < 2:
        return arr
    mid = len(arr) // 2
    left = arr[:mid]
    right = arr[mid:]
    return merge(mergeSort(left),mergeSort(right))

def merge(left,right):
    result = []
    while len(left)>0 and len(right)>0:
        if left[0] <= right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    result += left
    result += right
    return result

#快速排序方法
def quick_sort_standord(array, low, high):
    if low < high:
        key_index = partion(array, low, high)
        quick_sort_standord(array, low, key_index)
        quick_sort_standord(array, key_index + 1, high)

def partion(array, low, high):
    key = array[low]
    while low < high:
        while low < high and array[high] >= key:
            high -= 1
        if low < high:
            array[low] = array[high]
        while low < high and array[low] < key:
            low += 1
        if low < high:
            array[high] = array[low]
    array[low] = key
    return low
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值