到目前为止,这是heapsort计划。
public class HeapSort{
private static int[] a;
private static int n;
private static int left_child;
private static int right_child;
private static int largest;
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("What size of an array would you like?");
int y = input.nextInt();
int[] heapvictim = new int[y];
for (int z=0;z<heapvictim.length;z++)
{
System.out.println("Insert Integer at Array["+z+"]");
heapvictim[z] = input.nextInt();
}
System.out.println("Unsorted Array:");
for(int z=0;z<heapvictim.length;z++)
System.out.print(heapvictim[z]+" ");
System.out.println();
System.out.println("Sorted Array:");
sort(heapvictim);
for(int i=0;i<heapvictim.length;i++){
System.out.print(heapvictim[i] + " ");
}
}
public static void sort(int []a0){
a=a0;
buildheap(a);
for(int i=n;i>0;i--){
exchange(0, i);
n=n-1;
maxheapify(a, 0);
}
}
public static void buildheap(int []a){
n=a.length-1;
for(int i=n/2;i>=0;i--){
maxheapify(a,i);
}
}
public static void maxheapify(int[] a, int i){
left_child=2*i+1;
right_child=2*i+2;
if(left_child <= n && a[left_child] > a[i]){
largest=left_child;
}
else{
largest=i;
}
if(right_child <= n && a[right_child] > a[largest]){
largest=right_child;
}
if(largest!=i){
exchange(i,largest);
maxheapify(a, largest);
}
}
public static void exchange(int i, int j){
int t=a[i];
a[i]=a[j];
a[j]=t;
}
}
在maxheapify函数中,要确定是否向下堆积到左或右子,它会进行两次比较。对于最坏的情况,这意味着它将对树的高度(lg(n))进行两次比较。这意味着maxheapify的成本为2 * lg(n)。如何更改maxheapify以便它只需要大约1 * lg(n)?
我得到了一个提示,说我可以递归地使用二进制搜索,但我没有丝毫的线索如何这样做。
我感谢任何帮助/见解!