美文网首页
排序算法总结

排序算法总结

作者: 钱晓缺 | 来源:发表于2022-01-15 23:03 被阅读0次

    merge:

    class Solution(object):
        def sortArray(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            if len(nums) < 2:
                return nums
            mid = len(nums) // 2
            left = self.sortArray(nums[: mid])
            right = self.sortArray(nums[mid: ])
            return self.merge_sort(left, right)
        def merge_sort(self, left, right):
            startleft = 0
            startright = 0
            res = []
            while startleft < len(left) and  startright < len(right):
                if left[startleft] < right[startright]:
                    res.append(left[startleft])
                    startleft += 1
                else:
                    res.append(right[startright])
                    startright += 1
            res += left[startleft:]
            res += right[startright:]
            return res
    

    quick sort:

        def quicksort(self, nums):
                if len(nums) < 2:
                    return nums
                base = nums[0]
                less = [i for i in nums[1:] if i < base]
                more = [i for i in nums[1:] if i >= base]
                return self.quicksort(less) + [base] + self.quicksort(more)
    

    相关文章

      网友评论

          本文标题:排序算法总结

          本文链接:https://www.haomeiwen.com/subject/uzvxhrtx.html