go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  Heap Sort -- O(n*logn)
 
Subject: Heap Sort -- O(n*logn)
Author: Alex_Raj
In response to: Insertion Sort -- O(n^2)
Posted on: 12/27/2013 02:00:13 AM

/**
 *  Average case performance: O(nlogn)
 *  Best case performance:    O(nlogn)
 *  Worst case performance:   O(nlogn)
 */
public class HeapSort {
    
    /**
     * @param a Array of integers which are sorted when returns.
     */
    public static void sort(int[] a){
        
        /* Insertion onto heap */
        for(int k=0; k<a.length; k++){
            int n = k;
            while(n>0){
                int p = (n-1)/2; // parent
                if(a[n]>a[p]){
                    swap(a, n, p);
                    n = p;
                }else{
                    break;
                }
            }
        }
        
        /* Removal from heap */
        for(int k=a.length-1; k>0; k--){
            swap(a, 0, k);
            maxHeap(a, k, 0);
        }
    }
    
    /**
     * @param a Array of integers
     * @param size The heapsize
     * @param p The starting point/parent to heapify
     */
    private static void maxHeap(int[] a, int size, int p)
    {
        int left  = 2*p + 1;
        int right = left + 1;
        
        // leaf node
        if(left>=size)
            return;
        // node with only left child
        if(right>=size){
            if(a[left]>a[p]){
                swap(a, left, p);
            }
            return;
        }
        
        // find the largest among node, left child and right child.
        int largest = p;
        if(a[left]>a[p])
            largest = left;
        if(a[right]>a[largest])
            largest = right;
        
        if(largest!=p){
            swap(a, p, largest);
            maxHeap(a, size, largest);
        }
    }
    
    private static void swap(int[] a, int j, int k) {
        int temp = a[j];
        a[j] = a[k];
        a[k] = temp;
    }

}


 

> On 12/27/2013 01:59:13 AM Alex_Raj wrote:

/**
 *  Average case performance: O(n^2)
 *  Best case performance:    O(n)
 *  Worst case performance:   O(n^2)
 */
public class InsertionSort {

    /**
     * @param a Array of integers which are sorted when returns.
     */
    public static void sort(int[] a)
    {
        if(a==null||a.length==0)
            return;
        
        int temp;
        for(int k=1; k<a.length; k++){
            temp = a[k];
            int j;
            for(j=i; j>0 && a[j-1]>temp; j--){
                a[j]=a[j-1];
            }
            a[j]=temp;
        }
    }
}





References:

 


 
Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.