Skip to content

Commit 302f50a

Browse files
Adding HeapSort
1 parent dca6142 commit 302f50a

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

Go/sorting/heapsort.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Parent : (i-1)/2
3+
Left Child: (2*parent)+1
4+
Right Child: (2*parent)+2
5+
6+
Note: The below code sorts the array in ascending order using max-heap! For descending, min-heap should be used
7+
*/
8+
9+
package sorting
10+
11+
import "fmt"
12+
13+
func HeapSort(arr []int) {
14+
n := len(arr)
15+
fmt.Println(arr)
16+
// Phase 1 : Building!
17+
//Starts from the mid because if 1 side is sorted - the order will automatically get sorted!
18+
for parent := n / 2; parent >= 0; parent-- {
19+
buildHeap(arr, n, parent)
20+
}
21+
22+
// Phase 2: Extraction
23+
for i := n - 1; i >= 1; i-- {
24+
arr[0], arr[i] = arr[i], arr[0]
25+
buildHeap(arr, i, 0)
26+
}
27+
}
28+
29+
func buildHeap(arr []int, n, parent int) {
30+
largestElementIndex := parent
31+
leftChild := parent*2 + 1
32+
rightChild := parent*2 + 2
33+
34+
if leftChild < n && arr[leftChild] > arr[largestElementIndex] {
35+
largestElementIndex = leftChild
36+
}
37+
if rightChild < n && arr[rightChild] > arr[largestElementIndex] {
38+
largestElementIndex = rightChild
39+
}
40+
41+
if largestElementIndex != parent {
42+
arr[largestElementIndex], arr[parent] = arr[parent], arr[largestElementIndex]
43+
buildHeap(arr, n, largestElementIndex)
44+
}
45+
46+
}

Go/sorting/heapsort_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Parent : (i-1)/2
3+
Left Child: (2*parent)+1
4+
Right Child: (2*parent)+2
5+
6+
Note: The below code sorts the array in ascending order using max-heap! For descending, min-heap should be used
7+
*/
8+
9+
package sorting
10+
11+
import (
12+
"reflect"
13+
"testing"
14+
)
15+
16+
func TestHeapSort(t *testing.T) {
17+
type args struct {
18+
arr []int
19+
}
20+
tests := []struct {
21+
name string
22+
args args
23+
passed []int
24+
}{
25+
{
26+
name: "test-01",
27+
args: args{
28+
arr: []int{3, 14, 10, 12, 24, 6, 2, 17},
29+
},
30+
passed: []int{2, 3, 6, 10, 12, 14, 17, 24},
31+
},
32+
{
33+
name: "test-02",
34+
args: args{
35+
arr: []int{10, 2, 1, 3, 12, 8, 20},
36+
},
37+
passed: []int{1, 2, 3, 8, 10, 12, 20},
38+
},
39+
}
40+
for _, tt := range tests {
41+
t.Run(tt.name, func(t *testing.T) {
42+
HeapSort(tt.args.arr)
43+
if !reflect.DeepEqual(tt.args.arr, tt.passed) {
44+
t.Errorf("Got:%v but want:%v", tt.args.arr, tt.passed)
45+
}
46+
})
47+
}
48+
}

0 commit comments

Comments
 (0)