Skip to content

Commit

Permalink
heap sort
Browse files Browse the repository at this point in the history
  • Loading branch information
giovannymassuia committed Jun 28, 2024
1 parent c357dbb commit 15a7d83
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
39 changes: 39 additions & 0 deletions go-dsa/sorting/heap_sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package sorting

type HeapSort struct{}

func (h *HeapSort) Sort(arr []int) {
h.heapifyArray(arr)

for i := len(arr) - 1; i >= 0; i-- {
arr[0], arr[i] = arr[i], arr[0]
h.heapify(arr, 0, i)
}
}

// heapifyArray the array as a max heap
func (h *HeapSort) heapifyArray(arr []int) {
for i := len(arr) / 2; i >= 0; i-- {
h.heapify(arr, i, len(arr))
}
}

// heapify
func (h *HeapSort) heapify(arr []int, i int, n int) {
ref := i
left := 2*i + 1
right := 2*i + 2

if left < n && arr[left] > arr[ref] {
ref = left
}

if right < n && arr[right] > arr[ref] {
ref = right
}

if ref != i {
arr[i], arr[ref] = arr[ref], arr[i]
h.heapify(arr, ref, n)
}
}
42 changes: 42 additions & 0 deletions go-dsa/sorting/heap_sort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package sorting

import (
"testing"
)

func TestHeapSort(t *testing.T) {

tests := []struct {
input []int
expected []int
}{
{[]int{10, 20, 15, 40, 50, 100, 25, 45}, []int{10, 15, 20, 25, 40, 45, 50, 100}},
{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}},
{[]int{10, 20, 15, 40, 50, 100, 25, 45, 5, 35}, []int{5, 10, 15, 20, 25, 35, 40, 45, 50, 100}},
}

heapSort := HeapSort{}
for _, test := range tests {
// given
actual := make([]int, len(test.input))
copy(actual, test.input)

// when
heapSort.Sort(actual)

// then
if !compareArray(actual, test.expected) {
t.Errorf("Test failed! Expected = %v, Actual = %v", test.expected, actual)
}
}
}

func compareArray(actual, expected []int) bool {
for i := 0; i < len(expected); i++ {
if actual[i] != expected[i] {
return false
}
}

return true
}

0 comments on commit 15a7d83

Please sign in to comment.