我有一个随机生成数据的测试程序是随机生成的,然后将它们传递给类Sorter的类构造函数。然后 Sorter 会对数据进行排序,并通过一个方法将其传回给 main 函数。我还实现了其他几种排序方法作为 Sorter 类的子类,它们工作得很好。所以我认为我的 Sorter 类没有问题。下面是使用堆排序时我的测试程序的输出。
数据:
48 96 71 81 78 72 93 52 67 70
排序数据:
48 71 81 78 72 67 52 93 70 96
如您所见,经过以下代码后,数据没有排序。下面是代码。
public class HeapSort extends Sorter{
private int[] heap;
private int size;
public HeapSort(int[] data){
super(data);
}
public void sort(){
constructHeap();
for(int i = size - 1; i >= 0; i--){
numbers[i] = extractMax();
}
}
public void constructHeap(){
size = numbers.length;
heap = new int[size];
for(int j = 0; j < size; j++) heap[j] = numbers[j];
for(int i = size/2 - 1; i >= 0; i--){
fixHeap(i, heap[i]);
}
}
public int extractMax(){
int max = heap[0];
fixHeap(0, heap[--size]);
return max;
}
public void fixHeap(int pos, int key){
if(left(pos) > size) heap[pos] = key; // if current position is leaf
else{
int largest = pos;
int r = right(pos);
int l = left(pos);
if(r < size && heap[largest] < heap[r]) largest = r;
if(l < size && heap[largest] < heap[l]) largest = l;
if(largest == pos) heap[pos] = key;
else{
heap[pos] = heap[largest];
fixHeap(largest, key);
}
}
}
public int left(int i){return 2*i+1;}
public int right(int i){return 2*i+2;}
}
编辑:下面是调试的代码。希望有人会发现它有用。
public class HeapSort extends Sorter{
private int[] heap;
private int size;
public HeapSort(int[] data){
super(data);
}
public void sort(){
constructHeap();
for(int i = size - 1; i >= 0; i--){
numbers[i] = extractMax();
}
}
public void constructHeap(){
size = numbers.length;
heap = new int[size];
for(int j = 0; j < size; j++) heap[j] = numbers[j];
for(int i = size/2 - 1; i >= 0; i--){
fixHeap(i);
}
}
public int extractMax(){
int max = heap[0];
heap[0] = heap[--size];
fixHeap(0);
return max;
}
public void fixHeap(int pos){
if(left(pos) < size){ // if current position is not leaf
int largest = pos;
int r = right(pos);
int l = left(pos);
if(r < size && heap[largest] < heap[r]) largest = r;
if(l < size && heap[largest] < heap[l]) largest = l;
if(largest != pos){
exchange(pos, largest);
fixHeap(largest);
}
}
}
public int left(int i){return 2*i+1;}
public int right(int i){return 2*i+2;}
public void exchange(int a, int b){
int temp = heap[a];
heap[a] = heap[b];
heap[b] = temp;
}
}