Skip to content

Commit

Permalink
add: heap sort 3 (Heapify)
Browse files Browse the repository at this point in the history
  • Loading branch information
yi-ge committed Sep 17, 2023
1 parent 24d9bc3 commit 32c01a9
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
34 changes: 33 additions & 1 deletion src/sort/heap_sort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,40 @@
#include <headers.hpp>
#include <max_heap.hpp>

template <typename T> void __shiftDown(T arr[], int n, int k) {
while (2 * k + 1 < n) {
int j = 2 * k + 1; // 在此轮循环中,arr[k]和arr[j]交换位置
if (j + 1 < n && arr[j + 1] > arr[j]) {
j += 1;
}
if (arr[k] >= arr[j]) {
break;
}
swap(arr[k], arr[j]);
k = j;
}
}

template <typename T> void heapSort(T arr[], int n) {
// heapify
// 从(最后一个元素的索引-1)/2开始
// 最后一个元素的索引 = n-1
for (int i = (n - 1 - 1) / 2; i >= 0; i--) {
__shiftDown(arr, n, i);
}

for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]);
__shiftDown(arr, i, 0);
}
}

class Solution {
public:
vector<int> heapSort(vector<int> &nums) {
::heapSort(&nums[0], nums.size());
return nums;
}
/**
* @brief 堆排序
* nlogn
Expand Down Expand Up @@ -32,7 +64,7 @@ class Solution {
* @param nums
* @return vector<int>
*/
vector<int> heapSort(vector<int> &nums) {
vector<int> heapSort2(vector<int> &nums) {
int n = nums.size();
int arr[n];
for (int i = 0; i < n; i++) {
Expand Down
2 changes: 1 addition & 1 deletion test/lib/lib_test.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// 执行编译时间:2023-09-17 14:49:28
// 执行编译时间:2023-09-17 15:52:26
#include <gtest/gtest.h>
#include <lib.hpp>

Expand Down
9 changes: 8 additions & 1 deletion test/sort/heap_sort_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,12 @@ TEST(堆排序, heapSort1) {
Solution solution;
vector<int> nums = {2, 1, 3, 5, 4};
vector<int> actionVec = {1, 2, 3, 4, 5};
EXPECT_THAT(solution.heapSort(nums), ::testing::ContainerEq(actionVec));
EXPECT_THAT(solution.heapSort1(nums), ::testing::ContainerEq(actionVec));
}

TEST(堆排序, heapSort2) {
Solution solution;
vector<int> nums = {2, 1, 3, 5, 4};
vector<int> actionVec = {1, 2, 3, 4, 5};
EXPECT_THAT(solution.heapSort2(nums), ::testing::ContainerEq(actionVec));
}

0 comments on commit 32c01a9

Please sign in to comment.