重要算法

def binaryfind(nums, target):
    if not nums:
        return -1
    start, end = 0, len(nums)-1
    while start+1 < end:
        mid = start + (end-start)//2
        if nums[mid]==target:
            start = mid
        elif nums[mid]<target:
            start = mid
        else:
            end = mid
        if nums[start] == target:
            return start
        if nums[end] == target:
            return end
    return -1


def quick_sort(data, start, end):
    # 快排原地排序,直接对原list排序,没有返回值
    if start>=end:
        return
    # 开始结束索引不能破坏
    left, right = start, end
    mid = start + (end-start)//2
    # 避免最坏情况出现
    pivot = data[mid]
    while left <= right:
        print("###",left, right, data)
        while left <= right and data[left]<pivot:
            left += 1
        while left <= right and data[right]>pivot:
            right -= 1
        # 两头找到均不满足条件的数,需要互换区间
        if left <= right:
            data[left], data[right] = data[right], data[left]
            left += 1
            right -= 1
#     print(start, right)
    # 小范围内再排序,上层循环的停止条件是right<left,所以此时最左端是right,右端是left
    quick_sort(data, start, right)
    quick_sort(data, left, end)
nums = [33,2,11,8,7,12]
quick_sort(nums, 0, len(nums)-1)
nums


# 二分合并k个有序数组
nums1 = [2,3,18,23,118,283]
nums2 = [4,7,8,19,26,77,1262]
nums3 = [1,19,29,33,67,88]
nums4 = [36,47,55,88,128,765]
data = [nums1, nums2, nums3, nums4]

def mergeKnums(nums):
    n = len(nums)
    
    return binarySelect(nums, 0, n-1)

def merge2nums(nums1, nums2):
    if not nums1: return nums2
    if not nums2: return nums1
    
    i, j = 0, 0
    result = []
    while i < len(nums1) and j < len(nums2):
        if nums1[i] < nums2[j]:
            result.append(nums1[i])
            i += 1
        else:
            result.append(nums2[j])
            j += 1
    return result

def binarySelect(nums, left, right):
    if left == right: return nums[left]
    mid = left + (right-left)//2
    print(left, mid, right)
    nums1, nums2 = binarySelect(nums, left, mid), binarySelect(nums, mid+1, right)
    return merge2nums(nums1, nums2)
    
merge2nums(nums1, nums2)
mergeKnums(data)

# 归并排序
def sort_nums(nums):
    if not nums:
        return
    return merge_sort(nums)

def merge_sort(nums):
    if len(nums) == 1:
        return nums
    mid = len(nums)//2

    left_data, right_data = nums[:mid], nums[mid:]
    return merge(merge_sort(left_data), merge_sort(right_data))
    
def merge(l1, l2):
    result = []
    while len(l1)>0 and len(l2)>0:
        if l1[0] < l2[0]:
            result.append(l1.pop(0))
        else:
            result.append(l2.pop(0))
    result += l1
    result += l2
    return result

        
data = [3,2,17,23,8,1,11,28,33]
res = sort_nums(data)
res

 

posted @ 2023-02-14 22:15  今夜无风  阅读(21)  评论(0编辑  收藏  举报