Monday, 14 August 2017

Heap Sort

Java program for implementation of Heap Sort

public class HeapSort
{
public void sort(int arr[])
{
int n = arr.length;
for(int i=1;i<arr.length;i++)
reheapUp(arr,i);
int l=arr.length-1;
while(l>=0)
{
   swap(arr,0,l);
   l--;
   reheapDown(arr,0,l);

}
}
    void reheapUp(int[] arr,int index)
    {
        int parent=(index-1)/2;
        if(parent>=0)
        {
            if(arr[parent]<arr[index])
            {
                swap(arr,parent,index);
                reheapUp(arr,parent);
            }
        }
    }
    void reheapDown(int[] arr,int root,int l)
    {
        int leftChild=2*root+1;
        int rightChild=2*root+2;
        int largestIndex=root;
        if(leftChild<=l && arr[leftChild]>arr[largestIndex])
        largestIndex=leftChild;
        if(rightChild<=l && arr[rightChild]>arr[largestIndex])
        largestIndex=rightChild;
        if(largestIndex!= root)
        {
            swap(arr,largestIndex,root);
            reheapDown(arr,largestIndex,l);
        }
    }
    /* A utility function to swap array values */
    void swap(int[] arr,int parent,int index)
    {
        int temp=arr[parent];
        arr[parent]=arr[index];
        arr[index]=temp;
    }

/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}

// Driver program
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = arr.length;

HeapSort ob = new HeapSort();
ob.sort(arr);

System.out.println("Sorted array is");
printArray(arr);
}
}

No comments:

Post a Comment