Q:

C Program For HEAP Sort In Ascending Order Also Show Complexity

belongs to collection: Sorting C Programs

0

Heap Sort is a popular and efficient sorting algorithm  in computer programming. Learning how to write the heap sort algorithm requires knowledge of two types of data structures - arrays and trees.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include

 main()
{
    int heap[10], no, i, j, c, root, temp;

    printf("\n Enter no of elements :");
    scanf("%d", &no);
    printf("\n Enter the nos : ");
    for (i = 0; i < no; i++)
       scanf("%d", &heap[i]);
    for (i = 1; i < no; i++)
    {
        c = i;
        do
        {
            root = (c - 1) / 2;          
            if (heap[root] < heap[c])
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            c = root;
        } while (c != 0);
    }

    printf("Heap array : ");
    for (i = 0; i < no; i++)
        printf("%d\t ", heap[i]);
    for (j = no - 1; j >= 0; j--)
    {
        temp = heap[0];
        heap[0] = heap[j];
        heap[j] = temp;
        root = 0;
        do
        {
            c = 2 * root + 1;
            if ((heap[c] < heap[c + 1]) && c < j-1)
                c++;
            if (heap[root]            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            root = c;
        } while (c < j);
    }
    printf("\n The sorted array is : ");
    for (i = 0; i < no; i++)
       printf("\t %d", heap[i]);
    printf("\n Complexity : \n Best case = Avg case = Worst case = O(n logn) \n");
}

 

Output:

Enter no of elements : 6

Enter the nos :-89

0

12

5

+56

78

Heap array :78   12   56   -89   5   0  

The sorted array is: -89   0   5   12   56   78

Best case =Avg case = Worst case = o(n log)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< C Program For MERGE Sort In Ascending Order...