Skip to content

Added HeapSort to the deck #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions HeapSort/HeapSort.go
Original file line number Diff line number Diff line change
@@ -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
}
26 changes: 26 additions & 0 deletions HeapSort/HeapSort_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
}
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down