Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Program to Implement struct binaryheap Queue using Min Heap
- #include <stdio.h>
- #include <conio.h>
- //Min heap Declaration
- struct binaryheap
- {
- int maxsize;
- int size;
- int *elements;
- }h;
- //Function to Check Whether Heap is Empty
- int isempty()
- {
- if(h.size==0)
- return 1;
- else
- return 0;
- }
- //Function to Check Whether Heap is Full
- int isfull()
- {
- if(h.size==h.maxsize)
- return 1;
- else
- return 0;
- }
- //Function to display elements of the heap
- void display()
- {
- int i;
- if(isempty())
- {
- printf("\nThe Queue is empty!\n");
- }
- else
- {
- printf("\nThe Elements are: \n");
- for(i=1;i<=h.size;i++)
- {
- printf("\n%d",h.elements[i]);
- }
- }
- }
- //Function to insert elements to the heap
- void insert (int x)
- {
- int i,temp;
- if(h.size==0)
- {
- h.size++;
- h.elements[1]=x;
- }
- else
- {
- h.size++;
- h.elements[h.size]=x;
- for(i=h.size;h.elements[i]<h.elements[i/2]&&i/2!=0;i=i/2)
- {
- temp=h.elements[i];
- h.elements[i]=h.elements[i/2];
- h.elements[i/2]=temp;
- }
- }
- }
- //Function to delete the minimum element from the heap
- void delete_min()
- {
- int i=1,x,last;
- if(isempty())
- {
- printf("\nQueue Empty!\n");
- }
- else
- {
- x=h.elements[1];
- last=h.elements[h.size];
- printf("\nThe Deleted Element is: %d\n",h.elements[1]);
- while(i*2<=h.size)
- {
- if(h.elements[i*2]<h.elements[i*2+1])
- {
- h.elements[i]=h.elements[i*2];
- i=i*2;
- }
- else
- {
- h.elements[i]=h.elements[i*2+1];
- i=i*2+1;
- }
- }
- h.elements[i]=last;
- h.size--;
- }
- }
- int main()
- {
- int temp,ch,i;
- h.size=0;
- printf("\nEnter Maximum Number of Elements in the Queue: ");
- scanf("%d",&h.maxsize);
- h.elements=(int *)malloc((h.maxsize+1)*sizeof(int));
- menu:
- printf("\nMenu:\n1. Insert Elements\n2. Display Heap\n3. Delete Minimum Element\n4. Exit\nEnter Choice.....");
- scanf("%d",&ch);
- switch(ch)
- {
- case 1:
- do{
- if(!isfull())
- {
- printf("\nEnter the element: ");
- scanf("%d",&temp);
- insert(temp);
- }
- else
- {
- printf("\nQueue Full!\n");
- goto menu;
- }
- printf("\nInsert More ? Yes (1) No (0)");
- scanf("%d",&ch);
- }while(ch);
- break;
- case 2:
- display();
- break;
- case 3:
- delete_min();
- break;
- case 4:
- printf("\nThank You!");
- getch();
- return 0;
- default:
- printf("\nInvalid choice!\n");
- goto menu;
- }
- goto menu;
- }
Add Comment
Please, Sign In to add comment