我的 HeapSort 返回一个顺序不正确的数组。我的原始数组是 {15, 9, 11, 5, 6, 7},当运行 heapSort 方法时,我得到这个数组:{15, 11, 9, 6, 7, 5}。
我打印了该方法以查看 maxHeap 做了什么并得到了:{15, 9, 11, 5, 6, 7},当映射到二叉树中时,它实际上是一个 maxHeap。这让我相信排序方法或 buildMaxHeap 方法有问题。
public class heaps
{
public void maxHeap(int arr[], int index, int n)
{
int largest = index;
n = arr.length;
int l = (2*index) + 1;
int r =(2*index) + 2;
int size = arr.length;
if ((l < n) && (arr[l] > arr[largest]))
{
largest = l;
}
else
{
largest = index;
}
if ((r < size) && arr[r] > (arr[largest]))
{
largest = r;
}
if (largest != index)
{
int temp = arr[index];
arr[index] = arr[largest];
arr[largest] = temp;
maxHeap(arr, largest, n);
}
}
public void buildMaxHeap(int arr[])
{
int n = arr.length;
for (int index = (n / 2) - 1; index >= 0; index--)
{
maxHeap(arr, index, n);
}
}
public void sort(int arr[])
{
int n = arr.length;
buildMaxHeap(arr);
for (int index = n - 1; index >= 0; index--)
{
int temp = arr[0];
arr[0] = arr[index];
arr[index] = temp;
n = n - 1;
maxHeap(arr, index, 0);
}
}
public void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String[] args)
{
heaps o = new heaps();
int array[] = {15, 9, 11, 5, 6, 7};
heaps.sort(array);
heaps.printArray(array);
heaps.maxHeap(array, 0, array.length);
heaps.printArray(array);
}
}