How can I lower the cost of Heapsorts' Maxheap function from 2lg(n) to ~lg(n)? (Java)

134 Views Asked by At

Here is the heapsort program so far.

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; 
    }
}

In the maxheapify function, to determine whether to heapify down to the left or right child it does two comparisons. For the worst case this would mean that it would do two comparisons times the height of the tree ( lg(n) ). This means that maxheapify has a cost of 2*lg(n). How can I change maxheapify so that it would only require around 1*lg(n)?

I got a hint saying that I can use binarysearch recursively, but I haven't the slightest clue how to do so.

I appreciate any help/insight!

1

There are 1 best solutions below

0
On

I don't think so. In heapify, you have to find the minimum/maximum of 3 nodes - parent, left child and right child. How can you find the minimum of 3 in a single comparison?

Anyways, you'll get much better performance if you remove the recursion and put it inside a loop - assuming it doesn't get tail optimized already.

If you're still curious, take a look at this and this fast implementation.