Algorithm-Sort LC

1 Merge Sort

# python .pop .append
def mergeSort(arr):
    arr_len = len(arr)
    if arr_len < 2:
        return arr
    mid = arr_len // 2
    arr_left, arr_right = arr[0: mid], arr[mid:]
    return MGS(mergeSort(arr_left), mergeSort(arr_right))

def MGS(arr_left, arr_right):
    arr = []
    while arr_left and arr_right:
        if arr_left[0] <= arr_right[0]:
            arr.append(arr_left.pop(0))
        else:
            arr.append(arr_right.pop(0))
    while arr_left:
        arr.append(arr_left.pop(0))
    while arr_right:
        arr.append(arr_right.pop(0))
    return arr

2 Quick Sort

def quickSort1(arr, start, end):
    if start >= end:
        return
    low = start
    high = end
    mid = arr[start]
    while low < high:
        while low < high and arr[high] >= mid:
            high -= 1
        arr[low] = arr[high]
        while low < high and arr[low] < mid:
            low += 1
        arr[high] = arr[low]
    arr[low] = mid
    quickSort(arr, start, low - 1)
    quickSort(arr, low + 1, end)
    return arr
# use python .remove  .append
def quickSort2(arr):
    if len(arr) >= 2:
        mid = arr[len(arr) // 2]
        left, right = [], []
        arr.remove(mid)
        for num in arr:
            if num >= mid:
                right.append(num)
            else:
                left.append(num)
        return quickSort2(left) + [mid] + quickSort2(right)
    else:
        return arr
def quickSort3(arr):
# shorter lines
    if len(arr) < 2:
        return arr
    else:
        mid = arr[0]
        right = [i for i in arr[1:] if i >= mid]
        left = [i for i in arr[1:] if i < mid]
        return quickSort3(left) + [mid] + quickSort3(right)

3 Heap Sort

def heapSort(arr):
    def bigHeap(arr, father_node, length):
        father, son_left = father_node, father_node * 2 + 1
        while son_left < length:
            if son_left + 1 < length and arr[son_left + 1] > arr[son_left]:
                son_left += 1
            if arr[father] >= arr[son_left]:
                break
            arr[father], arr[son_left] = arr[son_left], arr[father]
            father, son_left = son_left, son_left * 2 + 1
    arr_len = len(arr)
    for father_i in range(arr_len // 2 -1 , -1, -1):
        bigHeap(arr, father_i, arr_len)
    for node_last in range(arr_len-1, -1, -1):
        arr[0], arr[node_last] = arr[node_last], arr[0]
        bigHeap(arr, 0, node_last)
    return arr
    ```

猜你喜欢

转载自blog.csdn.net/minovophy/article/details/121462814