我有这两个类,我想问关于
对于
这是第一个类
如何编写
heapSort()
方法的实现,如何在Test
类中进行实现?同时,你能否检查我的add()
方法和smallestChild()
方法吗?对于
heapSort()
方法,该方法应按升序对数组进行排序。算法是遍历数组并将所有数字添加到数组中,然后删除所有数字并将它们放回数组中!老实说,这个算法让我很困惑,我不知道该怎么做?heapSort()
是否需要一个辅助方法?还是怎样的方式?这是第一个类
MinHeap
。import java.util.NoSuchElementException;
public class MinHeap {
private int[] heap; // The heap.
private int size; // the next index
public MinHeap(int capacity) {
heap = new int[capacity];
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void add(int n) {
if (size < heap.length) {
size++;
n = heap[size-1];
int p = (size -1)/2;
while(n != 0 && n < heap[p]) {
swap(size, p);
size = p;
p=(size-1)/2;
}
size++;
} else {
throw new HeapFullException();
}
}
private int smallestChild(int current) {
if(size < heap.length) {
int left = current *2+2;
int right = current * 2 +1;
if(heap[left]>heap[right]) {
return left;
} else if(heap[right]>heap[left]) {
return right;
} else {
return left;
}
} else {
return -1;
}
}
public int remove() {
if (size == 0) {
// if size has no element to remove throw exception
throw new NoSuchElementException();
} else {
// hold the minimum element
int minElement = heap[0];
// set the minimum index to the highest index and decrement the size
heap[0] = heap[size-1];
size--;
int p = 0;
while(heap[p] > heap[smallestChild(p)]) {
int c = smallestChild(p);
swap(p, c);
p = c;
}
return minElement;
}
}
public String toString() {
String s = "";
for(int i=0; i<size; i++) {
s += i + ": " + heap[i] + "\n";
}
return s;
}
public int[] toArray() {
int[] a = new int[size];
for(int i=0; i<size; i++) {
a[i] = heap[i];
}
return a;
}
private void swap(int x, int y) {
int temp = heap[x];
heap[x] = heap[y];
heap[y] = temp;
}
class HeapFullException extends RuntimeException {
public static final long serialVersionUID = 8320632366082135L;
}
}
我应该在Test
类中编写sortHeap()
方法:
import java.util.Random;
public class Test {
private static Random rand = new Random();
public static void main(String[] args) {
testMinHeap();
}
public static void testMinHeap(){
int[] a = initRandom();
MinHeap h = new MinHeap(a.length);
for(int i=0; i<a.length; i++) {
h.add(a[i]);
}
print(a);
System.out.println("Smallest: " + h.remove());
int[] b = h.toArray();
print(b);
}
private static int[] initRandom() {
int[] a = new int[rand.nextInt(40)];
for(int i=0; i<a.length; i++) {
a[i] = rand.nextInt(100);
}
return a;
}
private static void print(int[] a) {
for(int i=0; i<a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
如何编写
sortHeap()
?请帮助我理解并为我的考试做好准备。谢谢。