算法第二天温故知新之小和问题、荷兰国旗问题和随机快排

不打扰是莪最后的温柔 提交于 2020-04-07 02:19:07

1、小和问题

# 引申自归并排序
import random


def merge_sort(arr):
    res = merge_fun1(arr)
    for i in range(0, len(arr)):
        arr[i] = res[i]
    return arr


def merge_fun1(arr):
    if len(arr) < 2:
        return arr
    mid = len(arr) // 2
    left_arr = merge_fun1(arr[:mid])
    right_arr = merge_fun1(arr[mid:])

    res = []
    left_point, right_point = 0, 0
    global little_sum
    while left_point < len(left_arr) and right_point < len(right_arr):
        if left_arr[left_point] < right_arr[right_point]:
            little_sum += (len(right_arr) - right_point) * left_arr[left_point]
            res.append(left_arr[left_point])
            left_point += 1
        else:
            res.append(right_arr[right_point])
            right_point += 1
    res += left_arr[left_point:]
    res += right_arr[right_point:]
    return res


# for test
def generate_random_array(max_size, max_value):
    arr = random.choices(range(0, max_value), k=random.randint(0, max_size))
    return arr


little_sum = 0
arr = generate_random_array(max_size=10, max_value=10)
print(arr)
merge_sort(arr)
# print(arr)
print(little_sum)

2、荷兰国旗问题

def partition(arr, num):
    left_border = -1
    right_border = len(arr)
    cur = 0
    while cur < right_border:
        if arr[cur] < num:
            left_border += 1
            arr[left_border], arr[cur] = arr[cur], arr[left_border]
            cur += 1
        elif arr[cur] > num:
            right_border -= 1
            arr[right_border], arr[cur] = arr[cur], arr[right_border]
        else:
            cur += 1
    return arr

3、随机快排

# 引申自荷兰国旗问题
def quick_sort(arr):
    if arr == [] and len(arr) < 2:
        return arr
    quick_sort_func(arr, 0, len(arr)-1)


def quick_sort_func(arr, l, r):
    if l < r:
        random_num = random.randint(l, r)
        arr[random_num], arr[r] = arr[r], arr[random_num]
        p = partition(arr, l, r)
        quick_sort_func(arr, l, p[0] - 1)
        quick_sort_func(arr, p[1] + 1, r)


def partition(arr, l, r):
    left_border = l - 1
    right_border = r
    while l < right_border:
        if arr[l] < arr[r]:
            left_border += 1
            arr[left_border], arr[l] = arr[l], arr[left_border]
            l += 1
        elif arr[l] > arr[r]:
            right_border -= 1
            arr[right_border], arr[l] = arr[l], arr[right_border]
        else:
            l += 1
    arr[right_border], arr[r] = arr[r], arr[right_border]
    return [left_border+1, right_border]

4、排序小结

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!