From 15a7d839e23304be7790dc85925752db5d04ce13 Mon Sep 17 00:00:00 2001 From: Giovanny Massuia Date: Fri, 28 Jun 2024 07:26:15 -0700 Subject: [PATCH] heap sort --- go-dsa/sorting/heap_sort.go | 39 +++++++++++++++++++++++++++++ go-dsa/sorting/heap_sort_test.go | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 go-dsa/sorting/heap_sort.go create mode 100644 go-dsa/sorting/heap_sort_test.go diff --git a/go-dsa/sorting/heap_sort.go b/go-dsa/sorting/heap_sort.go new file mode 100644 index 0000000..146ec7b --- /dev/null +++ b/go-dsa/sorting/heap_sort.go @@ -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) + } +} diff --git a/go-dsa/sorting/heap_sort_test.go b/go-dsa/sorting/heap_sort_test.go new file mode 100644 index 0000000..bdb21fb --- /dev/null +++ b/go-dsa/sorting/heap_sort_test.go @@ -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 +}