diff --git a/.idea/Algorithm.iml b/.idea/Algorithm.iml index e91ef14..ce6a017 100644 --- a/.idea/Algorithm.iml +++ b/.idea/Algorithm.iml @@ -2,9 +2,10 @@ + - + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index a1bbe46..2a8fcac 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,7 @@ - + + + \ No newline at end of file diff --git a/learn_sort/__init__.py b/learn_sort/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/learn_sort/heap.py b/learn_sort/heap.py new file mode 100644 index 0000000..ad415ff --- /dev/null +++ b/learn_sort/heap.py @@ -0,0 +1,31 @@ +def heapify(nums, start, end): + parent = start + son = parent * 2 + 1 + while son <= end: + if son + 1 <= end and nums[son] < nums[son + 1]: + son += 1 + if nums[parent] > nums[son]: + return + else: + nums[parent], nums[son] = nums[son], nums[parent] + parent = son + son = parent * 2 + 1 + + +def heap_sort(nums): + n = len(nums) + for i in range(n // 2 - 1, -1, -1): + heapify(nums, i, n - 1) + print(nums) + + for i in range(n - 1, 0, -1): + nums[0], nums[i] = nums[i], nums[0] + heapify(nums, 0, i - 1) + print(nums) + + +if __name__ == '__main__': + # https://leetcode.cn/problems/sort-an-array/description/ + _nums = [7, 10, 13, 15, 4, 20, 19, 8] + heap_sort(_nums) + print(_nums)