Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct entity{ //An entity consists has its data and its priority
- int data;
- int priority;
- };
- int heapsize;
- void swap(int *a ,int *b){
- int temp = *a; *a = *b; *b = temp;
- }
- void min_heapify(struct entity a[], int p){
- int r = (p+1)*2, l=r-1, smallest = p; //p is parent, r is right child and l is left child
- if(l < heapsize && a[l].priority < a[p].priority) smallest = l;
- if(r < heapsize && a[r].priority < a[smallest].priority) smallest = r;
- if(smallest != p){
- swap(&a[p].data, &a[smallest].data); //swap child and parent if parent isn't the smallest
- swap(&a[p].priority, &a[smallest].priority);
- min_heapify(a, smallest); //Keep on calling same method until parent is the smallest
- }
- }
- void build_min_heap(struct entity a[]){
- for(int p = heapsize/2; p >= 0; p--) min_heapify(a, p);//heapsize/2+1 onwards are leaves
- }
- void heapsort(struct entity a[]){
- build_min_heap(a);//smallest priority will be at root
- for(int i = heapsize-1; i >= 1; i--){
- swap(&a[0].priority, &a[i].priority); //swap root and a[i]
- swap(&a[0].data, &a[i].data); //root may violate heap property, but children are minheaps
- heapsize--;//delete the element from the heap by decrementing the heap size
- min_heapify(a, 0);//Run minheapify as the heap might violate the heap property.
- }
- }
- int main(){
- int i, n;
- printf("Enter the size of the Queue: ");
- scanf("%d", &n);
- heapsize = n;
- struct entity *a = (struct entity*)malloc(sizeof(struct entity) * n);
- for(i = 0; i < n; i++){
- printf("\nEnter the number and its priority:-\n");
- scanf("%d%d", &a[i].data, &a[i].priority);
- }
- heapsort(a);
- for(int i = 0; i < n; i++)
- printf("\n%d\t(priority: %d)\n", a[i].data, a[i].priority);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement