快速排序与归并排序的递归实现方式(python)

快速排序的递归实现方式

import random
import time


def Partition(A, low, high):
    x = A[low]
    i = low + 1
    j = high
    while (i < j):
        while (A[i] <= x and i < high):
            i += 1
        while (A[j] > x and j > low):
            j -= 1
        if (i < j):
            temp = A[i]
            A[i] = A[j]
            A[j] = temp
            i += 1
            j -= 1
    A[low] = A[j]
    A[j] = x
    return j


def QuiteSort(A, low, high):
    if (high > low):
        m = Partition(A, low, high)
        QuiteSort(A, low, m - 1)
        QuiteSort(A, m + 1, high)
    return A


if __name__ == '__main__':
    a = []
    for i in range(1000000): #生成随机list
        a.append(random.randint(1, 100000000))
    print(a)
    t1 = time.time()
    print(QuiteSort(a, 0, len(a) - 1))
    print("Quitesort用时:",time.time() - t1,"秒") #排序时间分析

归并排序的递归实现

import random
import time


def merge(a, b):
    i = 0
    j = 0
    c = []
    total = len(a) + len(b)
    while (len(c) != total):
        if (i == len(a)):
            for x in range(len(b) - j):
                c.append(b[j])
                j += 1
            break
        if (j == len(b)):
            for x in range(len(a) - i):
                c.append(a[i])
                i += 1
            break
        if (a[i] <= b[j]):
            c.append(a[i])
            i += 1
        else:
            c.append(b[j])
            j += 1
    return c


def MergeSort(array):
    len_a = len(array)
    temp_low = []
    temp_high = []
    if len_a > 1:
        n = 0
        for elems in array:
            if n < (len_a - 1) / 2:
                temp_low.append(elems)
            else:
                temp_high.append(elems)
            n += 1
        temp_low1 = MergeSort(temp_low)
        temp_high1 = MergeSort(temp_high)
        return merge(temp_low1, temp_high1)

    if len_a == 1:
        return array


if __name__ == '__main__':
    a = []
    for i in range(1000000):
        a.append(random.randint(1, 100000000))
    print(a)
    t1 = time.time()
    print(MergeSort(a))
    t2 = time.time()
    print("用时: ", t2 - t1, "秒")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值