堆排序比我更狡猾
我正在尝试实现基于数组的堆排序,它对前几个排序但不完全排序,我不明白为什么。这是我正在处理的内容:
public class HeapSort{
static int[] numbers = new int[] { 0, 13, 8, 5, 10, 9, 15, 1, 2, 3, 6, 4, 12, 14, 7, 11 };
static int[] array = new int[16];
public static void main(String[] args) {
for (int i = 0; i < 15; i++) {
array[i] = numbers[i];
if (i > 1)
sort(i);
}
for (int i = 1; i < 15; i++) {
System.out.println(array[i]);
}
}
public static void sort(int i) {
int parentLocation = i / 2;
int childLocation = i;
int parentValue = array[parentLocation];
int childValue = array[childLocation];
if (childValue < parentValue) {
array[parentLocation] = childValue;
array[childLocation] = parentValue;
sort(parentLocation);
}
}
}
我确信我使用递归来回忆父级上的排序是错误的,但我不明白为什么?
TIA
I'm trying to implement a array based Heap Sort, its sorting the first few but not fully and I can't figure out why. Here is what I'm working with:
public class HeapSort{
static int[] numbers = new int[] { 0, 13, 8, 5, 10, 9, 15, 1, 2, 3, 6, 4, 12, 14, 7, 11 };
static int[] array = new int[16];
public static void main(String[] args) {
for (int i = 0; i < 15; i++) {
array[i] = numbers[i];
if (i > 1)
sort(i);
}
for (int i = 1; i < 15; i++) {
System.out.println(array[i]);
}
}
public static void sort(int i) {
int parentLocation = i / 2;
int childLocation = i;
int parentValue = array[parentLocation];
int childValue = array[childLocation];
if (childValue < parentValue) {
array[parentLocation] = childValue;
array[childLocation] = parentValue;
sort(parentLocation);
}
}
}
I'm sure that its a fault in my use of recursion to recall the sort on the parent but I can't see why?
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在 C# 中有这个最小堆实现,漂亮易于阅读。你的 impl 缺失了很多。比如堆化。看看它。希望有帮助。
I have this min heap implementation in c#, pretty easy to read. Your impl is missing a lot. such as heapify. Take a look at it. hope it helps.