【发布时间】:2020-03-26 05:40:16
【问题描述】:
所以我正在使用 Max Heaps 的 java 实现。我的 Insert、bubbleUp 和 deleteMax(单独)方法似乎工作正常,但我的 heapsort 方法(调用 deleteMax)不能按预期工作(它不会导致错误消息;它只是不排序它们按应有的顺序排列)。我已经包含了下面的代码。非常感谢您对理解问题的任何帮助。谢谢!
整个课程可以在:https://repl.it/repls/FrequentPartialBlockchain
'''
public int deleteMax(){
if(this.numNodes == 0)
throw new NoSuchElementException();
else if(this.numNodes == 1){
int elemToReturn = heapArr[0];
heapArr[0] = null;
return elemToReturn;
}
int elemToReturn = heapArr[0];
heapArr[0] = heapArr[numNodes-1];
heapArr[numNodes-1] = null;
this.numNodes--;
bubbleDown();
return elemToReturn;
}
private void bubbleDown(){
int n = 0;
int L = 2 * n + 1; // L will hold the index of the left child
while(L < this.numNodes - 1){
int max = L;
int R = L + 1; // R will hold the index of the right child
if(R < this.numNodes - 1){
if(heapArr[R] >= heapArr[L])
max++;
}
int temp;
if(heapArr[n] < heapArr[max]){
// swap
temp = heapArr[n];
heapArr[n] = heapArr[max];
heapArr[max] = temp;
n = max;
L = 2 * n + 1;
}
else{
break;
}
}
}
public static void heapsort(Integer[] arrayToSort){
MaxHeap tempHeap = new MaxHeap(arrayToSort);
for(int i = 0; i < tempHeap.numNodes; i++)
arrayToSort[i] = (Integer) tempHeap.deleteMax();
}
'''
【问题讨论】:
标签: java sorting heap heapsort