-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heapsort.c
84 lines (58 loc) · 1013 Bytes
/
Heapsort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
int c=0;
/* Function to swap two numbers in an array */
void swap(int arr[], int i, int j)
{
c++;
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/* Function to swap largest element in heap */
void maxheap(int arr[], int i,int N)
{
int left = 2*i+1 ;
int right = 2*i + 2;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i)
{
swap(arr, i, max);
maxheap(arr, max,N);
}
}
/* Function to build a heap */
void heapify(int arr[],int N)
{
int i;
for (i = N/2; i >= 0; i--)
maxheap(arr, i,N);
}
/* Sort Function */
void sort(int arr[],int N)
{
heapify(arr,N);
int i;
for (i = N; i > 0; i--)
{
swap(arr,0, i);
N = N-1;
maxheap(arr, 0,N);
}
}
main()
{
int n;
scanf("%d",&n);
int A[n];
int j=n,i;
for(i=0;i<n;i++)
scanf("%d",&A[i]);
sort(A,n);
for(i=0;i<n;i++)
printf("%d\t",A[i]);
printf("\n");
}