forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapsort.go
More file actions
99 lines (73 loc) · 1.94 KB
/
heapsort.go
File metadata and controls
99 lines (73 loc) · 1.94 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* Heap Sort is a comparison-based sorting method performed on a Heap data structure.
Here we build a max heap first to later sort the elements in the heap in ascending order.
*/
package main
import "fmt"
func max_heapify(arr []int, n int, i int) {
largest := i // Initialize largest as root
l := 2 * i + 1 // left child
r := 2 * i + 2 // right child
// If left child is larger than root
if l < n && arr[l] > arr[largest] {
largest = l
}
// If right child is larger than largest so far
if r < n && arr[r] > arr[largest] {
largest = r
}
// If largest is not root
if largest != i {
//swapping
arr[i], arr[largest] = arr[largest], arr[i]
// Recursively heapify the affected sub-tree
max_heapify(arr, n, largest)
}
}
func heapSort(arr []int, n int) {
// Build heap (rearrange array)
for i := n / 2 - 1; i >= 0; i-- {
max_heapify(arr, n, i)
}
// One by one extract an element from heap
for i := n - 1; i >= 0; i-- {
// Move current root to end
arr[0], arr[i] = arr[i], arr[0];
// call heapify on the reduced heap
max_heapify(arr, i, 0);
}
}
func printArray(arr []int, no int) {
//printing the sorted array
for i := 0; i < no; i++ {
fmt.Print(arr[i], " ")
}
}
func main() {
var n int
fmt.Println("Enter the number of elements :")
//accepting the number of elements from the user
fmt.Scan(&n)
arr := make([]int, n)
for i := 0; i < n; i++ {
//accepting input elements
fmt.Scan(&arr[i])
}
fmt.Println(arr)
fmt.Println("\nSorted array is")
heapSort(arr, n)
printArray(arr, n)
}
/* OUTPUT:
Enter the number of elements : 7
Enter the elements :
0
12
11
13
5
6
7
Original Array: [0 12 11 13 5 6 7]
Sorted array is
0 5 6 7 11 12 13
*/