C Program to Implement Min Heap

0
6
Adv1


Adv2

#embody <stdio.h>

#embody <stdlib.h>

  

struct Heap {

    int* arr;

    int dimension;

    int capability;

};

  

typedef struct Heap heap;

  

heap* createHeap(int capability, int* nums);

void insertHelper(heap* h, int index);

void heapify(heap* h, int index);

int extractMin(heap* h);

void insert(heap* h, int knowledge);

  

heap* createHeap(int capability, int* nums)

{

    

    heap* h = (heap*)malloc(sizeof(heap));

  

    

    if (h == NULL) {

        printf("Reminiscence error");

        return NULL;

    }

    

    h->dimension = 0;

    h->capability = capability;

  

    

    h->arr = (int*)malloc(capability * sizeof(int));

  

    

    if (h->arr == NULL) {

        printf("Reminiscence error");

        return NULL;

    }

    int i;

    for (i = 0; i < capability; i++) {

        h->arr[i] = nums[i];

    }

  

    h->dimension = i;

    i = (h->dimension - 2) / 2;

    whereas (i >= 0) {

        heapify(h, i);

        i--;

    }

    return h;

}

  

void insertHelper(heap* h, int index)

{

  

    

    

    int mum or dad = (index - 1) / 2;

  

    if (h->arr[parent] > h->arr[index]) {

        

        

        int temp = h->arr[parent];

        h->arr[parent] = h->arr[index];

        h->arr[index] = temp;

  

        

        insertHelper(h, mum or dad);

    }

}

  

void heapify(heap* h, int index)

{

    int left = index * 2 + 1;

    int proper = index * 2 + 2;

    int min = index;

  

    

    

    if (left >= h->dimension || left < 0)

        left = -1;

    if (proper >= h->dimension || proper < 0)

        proper = -1;

  

    

    

    if (left != -1 && h->arr[left] < h->arr[index])

        min = left;

    if (proper != -1 && h->arr[right] < h->arr[min])

        min = proper;

  

    

    if (min != index) {

        int temp = h->arr[min];

        h->arr[min] = h->arr[index];

        h->arr[index] = temp;

  

        

        

        heapify(h, min);

    }

}

  

int extractMin(heap* h)

{

    int deleteItem;

  

    

    if (h->dimension == 0) {

        printf("nHeap id empty.");

        return -999;

    }

  

    

    

    deleteItem = h->arr[0];

  

    

    h->arr[0] = h->arr[h->size - 1];

    

    h->size--;

  

    

    

    heapify(h, 0);

    return deleteItem;

}

  

void insert(heap* h, int knowledge)

{

  

    

    if (h->dimension < h->capability) {

        

        h->arr[h->size] = knowledge;

        

        insertHelper(h, h->dimension);

        

        h->dimension++;

    }

}

  

void printHeap(heap* h)

{

  

    for (int i = 0; i < h->dimension; i++) {

        printf("%d ", h->arr[i]);

    }

    printf("n");

}

  

int important()

{

    int arr[9] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

    heap* hp = createHeap(9, arr);

  

    printHeap(hp);

    extractMin(hp);

    printHeap(hp);

  

    return 0;

}

Adv3