File tree Expand file tree Collapse file tree 2 files changed +61
-13
lines changed Expand file tree Collapse file tree 2 files changed +61
-13
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change
1
+ #include <stdio.h>
2
+ #include <conio.h>
3
+ void heapify (int arr [],int n ,int i )
4
+ {
5
+ int max = i ; //parent node index
6
+ int left = 2 * i + 1 ; // left child node index
7
+ int right = 2 * i + 2 ; //right child node index
8
+ int temp ;
9
+ if (left < n && arr [left ]> arr [max ]) //if left child node is greater than parent
10
+ {
11
+ max = left ;
12
+ }
13
+ if (right < n && arr [right ]> arr [max ])
14
+ {
15
+ max = right ;
16
+ }
17
+ if (max != i )
18
+ {
19
+ temp = arr [i ]; //swapping the max element to the root node
20
+ arr [i ]= arr [max ];
21
+ arr [max ]= temp ;
22
+ heapify (arr ,n ,max ); //every node element
23
+ }
24
+ }
25
+
26
+
27
+ void heapsort (int arr [],int n )
28
+ {
29
+ int i ,temp ;
30
+
31
+ for (i = n /2 - 1 ;i >=0 ;i -- )
32
+ {
33
+ heapify (arr ,n ,i );
34
+ }
35
+ //swap the elements and heapify again
36
+ for (i = n - 1 ;i >=0 ;i -- )
37
+ {
38
+ temp = arr [0 ];
39
+ arr [0 ]= arr [i ];
40
+ arr [i ]= temp ;
41
+ heapify (arr ,i ,0 ); //root node swap from 0th index
42
+ }
43
+ }
44
+ int main ()
45
+ {
46
+ int arr [100 ],n ,i ;
47
+ printf ("\n Enter the n of the elements:" );
48
+ scanf ("%d" ,& n );
49
+ printf ("Enter the elements:" );
50
+ for (i = 0 ;i < n ;i ++ )
51
+ {
52
+
53
+ scanf ("%d" ,& arr [i ]);
54
+ }
55
+ heapsort (arr ,n );
56
+ printf ("The Heap Sorted Array is:" );
57
+ for (i = 0 ;i < n ;i ++ )
58
+ {
59
+ printf ("\t %d" ,arr [i ]);
60
+ }
61
+ }
You can’t perform that action at this time.
0 commit comments