堆排序
#908
Replies: 4 comments 3 replies
-
是否可以加上 C++ |
Beta Was this translation helpful? Give feedback.
1 reply
-
class Solution {
public int[] sortArray(int[] nums){
heapSort(nums);
return nums;
}
public void heapSort(int[] nums){
int len = nums.length;
// 建堆
for(int i = (len - 2) / 2; i >= 0; i--) {
heapify(nums, i, len - 1);
}
for(int i = len - 1; i > 0; i--) {
swap(nums, i, 0);
heapify(nums, 0, i - 1);
}
}
// 大顶堆 : 调整某个结点使得整个子树满足大顶堆要求
public void heapify(int[] nums, int root, int end){
int p = root;
int c = root * 2 + 1; // 左孩子
while(c <= end){
if(c + 1 <= end && nums[c] <= nums[c + 1]) c++;
if(nums[p] >= nums[c]) return ;
else {
swap(nums, p, c);
p = c;
c = p * 2 + 1;
}
}
}
public void swap(int[] nums, int i, int j){
int tmp = nums[i];
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
} 关于下标和边界条件的快速选择方法:画一棵树模拟一下 |
Beta Was this translation helpful? Give feedback.
1 reply
-
感觉C++代码第四行写错了,左儿子应该是 2*i |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
https://oi-wiki.org/basic/heap-sort/
OI Wiki 是一个编程竞赛知识整合站点,提供有趣又实用的编程竞赛知识以及其他有帮助的内容,帮助广大编程竞赛爱好者更快更深入地学习编程竞赛
Beta Was this translation helpful? Give feedback.
All reactions