From 0b0f6bd3c44da5f6dab4dadda0ac9430c693f404 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Fri, 17 Nov 2023 02:14:53 -0500 Subject: [PATCH] adding the heapify solution --- lectures/23_priority_queues_II/README.md | 1 + leetcode/p912_heapsort_array_heapify.cpp | 46 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 leetcode/p912_heapsort_array_heapify.cpp diff --git a/lectures/23_priority_queues_II/README.md b/lectures/23_priority_queues_II/README.md index aab450e..9b5cbce 100644 --- a/lectures/23_priority_queues_II/README.md +++ b/lectures/23_priority_queues_II/README.md @@ -119,3 +119,4 @@ organized heap data, but incur a O(n log n) cost. Why? ## 23.10 Leetcode Exercises - [Leetcode problem 912: Sort an Array](https://leetcode.com/problems/sort-an-array/). Solution: [p912_heapsort_array.cpp](../../leetcode/p912_heapsort_array.cpp). +Solution2: [p912_heapsort_array_heapify.cpp](../../leetcode/p912_heapsort_array_heapify.cpp). diff --git a/leetcode/p912_heapsort_array_heapify.cpp b/leetcode/p912_heapsort_array_heapify.cpp new file mode 100644 index 0000000..2496c1b --- /dev/null +++ b/leetcode/p912_heapsort_array_heapify.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + void heapify(vector& nums, int n, int i){ + int largest = i; // assuming i is the largest + int left = 2*i+1; // i's left child is at this location + int right = 2*i+2; // i's right child is at this location + + if(leftnums[largest]){ + largest = left; + } + + if(rightnums[largest]){ + largest = right; + } + + // after the above, largest basically will either stay the same, or will be either left or right, depending on nums[left] is larger or nums[right] is larger. largest stays the same if it is already larger than its two children. + // if largest is changed, then we do need to swap. + if(largest != i){ + std::swap(nums[i], nums[largest]); + heapify(nums, n, largest); + } + } + + // heap sort: O(nlogn) + vector sortArray(vector& nums) { + int n = nums.size(); + // build the heap, starting from the last non-leaf node + for(int i=n/2-1; i>=0; i--){ + // heapify the subtree whose root is at i + // i.e., build a max heap, with i being the root. + heapify(nums, n, i); + } + + // now the first one is the largest, swap it to the back + // do this n-1 times. + for(int i=0; i<(n-1); i++){ + // nums[0] is always the largest one + std::swap(nums[0], nums[n-1-i]); + // build the max heap again, with 0 being the root. + // but only consider n-1-i elements, as the others are already in the right place. + heapify(nums, n-1-i, 0); + } + + return nums; + } +};