Advertisement
Shailrshah

Priority Queue Using Heap

Nov 11th, 2013
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.84 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct entity{ //An entity consists has its data and its priority
  4.     int data;
  5.     int priority;
  6. };
  7. int heapsize;
  8. void swap(int *a ,int *b){
  9.     int temp = *a; *a = *b; *b = temp;
  10. }
  11. void min_heapify(struct entity a[], int p){
  12.     int r = (p+1)*2, l=r-1, smallest = p; //p is parent, r is right child and l is left child
  13.     if(l < heapsize && a[l].priority < a[p].priority) smallest = l;
  14.     if(r < heapsize && a[r].priority < a[smallest].priority) smallest = r;
  15.     if(smallest != p){
  16.         swap(&a[p].data, &a[smallest].data); //swap child and parent if parent isn't the smallest
  17.         swap(&a[p].priority, &a[smallest].priority);
  18.         min_heapify(a, smallest); //Keep on calling same method until parent is the smallest
  19.     }
  20. }
  21. void build_min_heap(struct entity a[]){
  22.     for(int p = heapsize/2; p >= 0; p--) min_heapify(a, p);//heapsize/2+1 onwards are leaves
  23. }
  24. void heapsort(struct entity a[]){
  25.     build_min_heap(a);//smallest priority will be at root
  26.     for(int i = heapsize-1; i >= 1; i--){
  27.         swap(&a[0].priority, &a[i].priority); //swap root and a[i]
  28.         swap(&a[0].data, &a[i].data); //root may violate heap property, but children are minheaps
  29.         heapsize--;//delete the element from the heap by decrementing the heap size
  30.         min_heapify(a, 0);//Run minheapify as the heap might violate the heap property.
  31.     }
  32. }
  33. int main(){
  34.     int i, n;
  35.     printf("Enter the size of the Queue: ");
  36.     scanf("%d", &n);
  37.     heapsize = n;
  38.     struct entity *a = (struct entity*)malloc(sizeof(struct entity) * n);
  39.     for(i = 0; i < n; i++){
  40.         printf("\nEnter the number and its priority:-\n");
  41.         scanf("%d%d", &a[i].data, &a[i].priority);
  42.     }
  43.     heapsort(a);
  44.     for(int i = 0; i < n; i++)
  45.         printf("\n%d\t(priority: %d)\n", a[i].data, a[i].priority);
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement