python中的quicksort 和mergesort

def quicksort(alist):
    return quicksorthelper(alist, 0 , len(alist)-1)
    
def quicksorthelper(alist, first, last):
    if first < last:
        splitpartition = partition(alist, first, last)
        quicksorthelper(alist, first , splitpartition-1)
        quicksorthelper(alist, splitpartition+1, last)
        
def partition(alist, first, last):
    pivot = alist[first]
    left, right = first + 1, last
    while left<=right:
        while left<=right and alist[left]<=pivot: left = left +1
        while left<=right and alist[right]>=pivot: right = right -1
        if left<=right: alist[left], alist[right] = alist[right],alist[left]
            
    alist[first], alist[right] = alist[right], alist[first]
    return right

#### MergeSort #####def mergesort(arr):
    if arr is None or len(arr) <=1:
        return arr
    mid = len(arr)//2
    left = mergesort(arr[:mid])
    right = mergesort(arr[mid:])
    return merge(left, right)
def merge(left,right):
    i, j = 0, 0
    result = []
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    
    result += left[i:]
    result += right[j:]
    return result

import random
arr = [ random.randint(0,100) for i in range (10)]
print("Original:", arr)
quicksort(arr)
print("Quick Sorted:", arr)
print()
arr = [ random.randint(0,100) for i in range (10)]
print("Original:", arr)
print("Merge Sorted:", arr)

#### Output ####
#Original: [91, 91, 96, 45, 80, 92, 98, 88, 28, 58]
#Quick Sorted: [28, 45, 58, 80, 88, 91, 91, 92, 96, 98]

#Original: [76, 50, 4, 20, 55, 50, 37, 55, 35, 60]
#Merge Sorted: [76, 50, 4, 20, 55, 50, 37, 55, 35, 60]
©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值