Skip to content
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

Added Heap Sort in Golang. #133

Merged
merged 1 commit into from
Oct 5, 2020
Merged
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
83 changes: 83 additions & 0 deletions Golang/sorting/heap_sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package main

import "fmt"

type minheap struct {
arr []int
}

func newMinHeap(arr []int) *minheap {
minheap := &minheap{
arr: arr,
}
return minheap
}

func (m *minheap) leftchildIndex(index int) int {
return 2*index + 1
}

func (m *minheap) rightchildIndex(index int) int {
return 2*index + 2
}

func (m *minheap) swap(first, second int) {
temp := m.arr[first]
m.arr[first] = m.arr[second]
m.arr[second] = temp
}

func (m *minheap) leaf(index int, size int) bool {
if index >= (size/2) && index <= size {
return true
}
return false
}

func (m *minheap) downHeapify(current int, size int) {
if m.leaf(current, size) {
return
}
smallest := current
leftChildIndex := m.leftchildIndex(current)
rightRightIndex := m.rightchildIndex(current)
if leftChildIndex < size && m.arr[leftChildIndex] < m.arr[smallest] {
smallest = leftChildIndex
}
if rightRightIndex < size && m.arr[rightRightIndex] < m.arr[smallest] {
smallest = rightRightIndex
}
if smallest != current {
m.swap(current, smallest)
m.downHeapify(smallest, size)
}
return
}

func (m *minheap) buildMinHeap(size int) {
for index := ((size / 2) - 1); index >= 0; index-- {
m.downHeapify(index, size)
}
}

func (m *minheap) sort(size int) {
m.buildMinHeap(size)
for i := size - 1; i > 0; i-- {
m.swap(0, i)
m.downHeapify(0, i)
}
}

func (m *minheap) print() {
for _, val := range m.arr {
fmt.Println(val)
}
}

func main() {
inputArray := []int{6, 5, 3, 7, 2, 8, -1}
minHeap := newMinHeap(inputArray)
minHeap.sort(len(inputArray))
minHeap.print()
fmt.Scanln()
}