<\/span><\/h1>\n\n\n\npackage main\n\nimport \"fmt\"\n\ntype minheap struct {\n arr []int\n}\n\nfunc newMinHeap(arr []int) *minheap {\n minheap := &minheap{\n arr: arr,\n }\n return minheap\n}\n\nfunc (m *minheap) leftchildIndex(index int) int {\n return 2*index + 1\n}\n\nfunc (m *minheap) rightchildIndex(index int) int {\n return 2*index + 2\n}\n\nfunc (m *minheap) swap(first, second int) {\n temp := m.arr[first]\n m.arr[first] = m.arr[second]\n m.arr[second] = temp\n}\n\nfunc (m *minheap) leaf(index int, size int) bool {\n if index >= (size\/2) && index <= size {\n return true\n }\n return false\n}\n\nfunc (m *minheap) downHeapify(current int, size int) {\n if m.leaf(current, size) {\n return\n }\n smallest := current\n leftChildIndex := m.leftchildIndex(current)\n rightRightIndex := m.rightchildIndex(current)\n if leftChildIndex < size && m.arr[leftChildIndex] < m.arr[smallest] {\n smallest = leftChildIndex\n }\n if rightRightIndex < size && m.arr[rightRightIndex] < m.arr[smallest] {\n smallest = rightRightIndex\n }\n if smallest != current {\n m.swap(current, smallest)\n m.downHeapify(smallest, size)\n }\n return\n}\n\nfunc (m *minheap) buildMinHeap(size int) {\n for index := ((size \/ 2) - 1); index >= 0; index-- {\n m.downHeapify(index, size)\n }\n}\n\nfunc (m *minheap) sort(size int) {\n m.buildMinHeap(size)\n for i := size - 1; i > 0; i-- {\n \/\/ Move current root to end\n m.swap(0, i)\n m.downHeapify(0, i)\n }\n}\n\nfunc (m *minheap) print() {\n for _, val := range m.arr {\n fmt.Println(val)\n }\n}\n\nfunc main() {\n inputArray := []int{6, 5, 3, 7, 2, 8, -1}\n minHeap := newMinHeap(inputArray)\n minHeap.sort(len(inputArray))\n minHeap.print()\n fmt.Scanln()\n}<\/code><\/pre>\n\n\n\nOutput:<\/strong><\/p>\n\n\n\n8\n7\n6\n5\n3\n2\n-1<\/code><\/pre>\n\n\n\n<\/p>\n\n\n\n
<\/span>Time Complexity<\/strong><\/span><\/h1>\n\n\n\nTime Complexity of Heap Sort is \u00a0O(nLogn).<\/p>\n","protected":false},"excerpt":{"rendered":"
Table of Contents IntroductionSteps for HeapSort:Full Working CodeTime Complexity Introduction HeapSort is a comparison-based sorting algorithm that uses the Heap Data Structure. Please refer to this link for more information about Heap…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[3,118,119],"class_list":["post-996","post","type-post","status-publish","format-standard","hentry","category-tech","tag-go","tag-heapsort","tag-heapsort-in-go"],"yoast_head":"\n
HeapSort in Golang - Welcome To Golang By Example<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n