diff --git a/HeapSort/HeapSort.go b/HeapSort/HeapSort.go new file mode 100644 index 0000000..9b96ae1 --- /dev/null +++ b/HeapSort/HeapSort.go @@ -0,0 +1,50 @@ +package HeapSort + +type Heap struct { +} + +func (heap *Heap) HeapSort(array []int) { + heap.BuildHeap(array) + + for length:= len(array); length > 1; length-- { + heap.RemoveTop(array, length) + } +} + +func (heap *Heap) BuildHeap(array []int) { + for i := len(array) / 2; i >= 0; i-- { + heap.Heapify(array, i, len(array)) + } +} + +func (heap *Heap) RemoveTop(array []int, length int) { + var lastIndex = length - 1 + array[0], array[lastIndex] = array[lastIndex], array[0] + heap.Heapify(array, 0, lastIndex) +} + +func (heap *Heap) Heapify(array []int, root, length int) { + var max = root + var l, r = heap.Left(array, root), heap.Right(array, root) + + if l < length && array[l] > array[max] { + max = l + } + + if r < length && array[r] > array[max] { + max = r + } + + if max != root { + array[root], array[max] = array[max], array[root] + heap.Heapify(array, max, length) + } +} + +func (*Heap) Left(array []int, root int) int { + return (root * 2) + 1 +} + +func (*Heap) Right(array []int, root int) int { + return (root * 2) + 2 +} diff --git a/HeapSort/HeapSort_test.go b/HeapSort/HeapSort_test.go new file mode 100644 index 0000000..0f6c675 --- /dev/null +++ b/HeapSort/HeapSort_test.go @@ -0,0 +1,26 @@ +package HeapSort + +import ( + "math/rand" + "sort" + "testing" + "time" +) + +func TestHeapSort(t *testing.T) { + random := rand.New(rand.NewSource(time.Now().UnixNano())) + array1 := make([]int, random.Intn(100-10)+10) + for i := range array1 { + array1[i] = random.Intn(100) + } + array2 := make(sort.IntSlice, len(array1)) + copy(array2, array1) + var heap = new(Heap) + heap.HeapSort(array1) + array2.Sort() + for i := range array1 { + if array1[i] != array2[i] { + t.Fail() + } + } +} diff --git a/README.md b/README.md index 90c81b4..5b7ac69 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ There are several data structures and algorithms implemented in this project. Th - Cocktail Sort - Gnome Sort - Merge Sort +- Heap Sort ## Usage