Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- int heapsize;
- void swap(int *a ,int *b){
- int temp = *a;
- *a = *b;
- *b = temp;
- }
- void max_heapify(int *a, int i){
- int l = 2*i, r = l+1, largest;
- if(l < heapsize && a[l] > a[i]) largest = l;
- else largest = i;
- if(r < heapsize && a[r] > a[largest]) largest = r;
- if(largest != i){
- swap(&a[i], &a[largest]);
- max_heapify(a, largest);
- }
- }
- void build_max_heap(int *a){
- for(int i = heapsize/2; i >= 0; i--) max_heapify(a, i);
- }
- void heapsort(int *a){
- build_max_heap(a);
- for(int i = heapsize-1; i >= 1; i--){
- swap(&a[0], &a[i]);
- heapsize--;
- max_heapify(a, 0);
- }
- }
- int main(){
- int i, n;
- printf("Number of elements: ");
- scanf("%d", &n);
- heapsize = n;
- int *a = (int*)malloc(sizeof(int) * n);
- for(i = 0; i < n; i++) scanf("%d", &a[i]);
- heapsort(a);
- for(i = 0; i < n; i++) printf("\t%d\t", a[i]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement