File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ var heapSize = 0
2
+
3
+ fun left (i : Int ): Int {
4
+ return 2 * i
5
+ }
6
+
7
+ fun right (i : Int ): Int {
8
+ return 2 * i + 1
9
+ }
10
+
11
+ fun swap (A : Array <Int >, i : Int , j : Int ) {
12
+ var temp = A [i]
13
+ A [i] = A [j]
14
+ A [j] = temp
15
+ }
16
+
17
+ fun max_heapify (A : Array <Int >, i : Int ) {
18
+ var l = left(i);
19
+ var r = right(i);
20
+ var largest: Int ;
21
+
22
+ if ((l <= heapSize - 1 ) && (A [l] > A [i])) {
23
+ largest = l;
24
+ } else
25
+ largest = i
26
+
27
+ if ((r <= heapSize - 1 ) && (A [r] > A [l])) {
28
+ largest = r
29
+ }
30
+
31
+ if (largest != i) {
32
+ swap(A , i, largest);
33
+ max_heapify(A , largest);
34
+ }
35
+ }
36
+
37
+ fun buildMaxheap (A : Array <Int >) {
38
+ heapSize = A .size
39
+ for (i in heapSize / 2 downTo 0 ) {
40
+ max_heapify(A , i)
41
+ }
42
+ }
43
+
44
+ fun heap_sort (A : Array <Int >) {
45
+ buildMaxheap(A )
46
+ for (i in A .size - 1 downTo 1 ) {
47
+ swap(A , i, 0 )
48
+ heapSize = heapSize - 1
49
+ max_heapify(A , 0 )
50
+
51
+ }
52
+ }
53
+
54
+ fun main (arg : Array <String >) {
55
+ print (" Enter no. of elements :" )
56
+ var n = readLine()!! .toInt()
57
+
58
+ println (" Enter elements : " )
59
+ var A = Array (n, { 0 })
60
+ for (i in 0 until n)
61
+ A [i] = readLine()!! .toInt()
62
+
63
+ heap_sort(A )
64
+
65
+ println (" Sorted array is : " )
66
+ for (i in 0 until n)
67
+ print (" ${A [i]} " )
68
+ }
You can’t perform that action at this time.
0 commit comments