我正在做我的算法的中期审查,我试图用 Java 实现所有的伪代码,以便更好地理解算法。但是在堆排序部分,我的代码有问题。我的输入数组是
{10,16,4,10,14,7,9,3,2,8,1}
第一个元素只代表我想要排序的元素数量。换句话说,需要排序的元素从索引 1 开始。
我构建最大堆的输出是:16 14 10 8 7 9 3 2 4 1
我的堆排序输出是:1 3 2 4 7 8 9 10 14 16
看起来我的 build-max-heap 部分运行良好,但我也找不到堆排序部分的错误。
public class Midterm{
public static void main(String[] args){
int[] C = {10,16,4,10,14,7,9,3,2,8,1};
/*for convenience, the first element in array C represent the
number of elements needed to be heapified;
*/
Midterm heap = new Midterm();
int n = C.length - 1;
for (int i = (n / 2); i > 0; i--){
heap.maxHeapify(C, i, n);
}
int index = 1;
while(index <= n){
System.out.print(C[index] + " ");
index++;
}
System.out.println();
Midterm heap2 = new Midterm();
heap2.heapSort(C);
int index2 = 1;
while(index2 <= n){
System.out.print(C[index2] + " ");
index2++;
}
System.out.println();
}
public void heapSort(int[] A){
int n = A.length - 1;
for (int i = n; i >= 2; i--){
exchange(A, 1, i);
maxHeapify(A, 1, i - 1);
}
}
public void maxHeapify(int[] A, int i, int n){
int left = 2 *i, right = 2 * i + 1;
int largest;
if (left < n && A[left] > A[i]){
largest = left;
}else{
largest = i;
}
if (right < n && A[right] > A[largest]){
largest = right;
}
if (largest != i){
exchange(A, i, largest);
maxHeapify(A, largest,n);
}
}
private void exchange(int[] A, int i , int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}