gpt4 book ai didi

java - 我的堆排序只排列在数组的特定间隔

转载 作者:行者123 更新时间:2023-11-30 11:46:12 25 4
gpt4 key购买 nike

堆排序有问题。好像只有每4个间隔排列一次。我得到的输出是:

167548
1092841
11047435
23672988
3901457
13705876
32329454
62936411
34097325
45417546
23189907
50261310
184562247

代码:

public static <T extends Comparable<? super T>> void reheap(T[] heap, int rootIndex, int lastIndex) {

boolean done = false;
T orphan = heap[rootIndex];
int leftChildIndex = 2 * rootIndex + 1;

while (!done && (leftChildIndex <= lastIndex)) {
int largerChildIndex = leftChildIndex;
int rightChildIndex = leftChildIndex + 1;
if ((rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[largerChildIndex]) > 0) {
largerChildIndex = rightChildIndex;
}

if (orphan.compareTo(heap[largerChildIndex]) < 0) {
heap[rootIndex] = heap[largerChildIndex];
rootIndex = largerChildIndex;
leftChildIndex = 2 * rootIndex + 1;

} else
done = true;
}
heap[rootIndex] = orphan;
}

public static <T extends Comparable<? super T>> void heapsort(T[] array, int n) {
for (int rootIndex = n / 2 - 1; rootIndex >= 0; rootIndex--) {

reheap(array, rootIndex, n - 1);
swap(array, 0, n - 1);

for (int lastIndex = n - 2; lastIndex > 0; lastIndex--) {
reheap(array, 0, lastIndex);
swap(array, 0, lastIndex);

}
}
}

public static void swap(Object[] array, int i, int j) {
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
}

最佳答案

我不确定这是否是最佳解决方案,但您可以尝试将内部 for-loop 移出:

public static <T extends Comparable<? super T>> void heapsort(T[] array, int n) {
for (int rootIndex = n / 2 - 1; rootIndex >= 0; rootIndex--) {
reheap(array, rootIndex, n - 1);
swap(array, 0, n - 1);
}

for (int lastIndex = n - 2; lastIndex > 0; lastIndex--) {
reheap(array, 0, lastIndex);
swap(array, 0, lastIndex);
}
}

关于java - 我的堆排序只排列在数组的特定间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9934899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com