Heap Sort (With Code in Python, C++, Java and C) - Programiz
文章推薦指數: 80 %
Heap sort works by visualizing the elements of the array as a special kind of complete binary tree called a heap. Note: As a prerequisite, you must know ...
CourseIndex
ExploreProgramiz
Python
JavaScript
SQL
C
C++
Java
Kotlin
Swift
C#
DSA
PopularTutorials
QuicksortAlgorithm
MergeSortAlgorithm
LinkedListDataStructure
HashTableDataStructure
DynamicProgramming
StartLearningDSA
LearningPaths
Challenges
LearnPythonInteractively
TryforFree
Courses
BecomeaPythonMaster
BecomeaCMaster
BecomeaJavaMaster
ViewallCourses
Python
JavaScript
SQL
C
C++
Java
Kotlin
Swift
C#
DSA
PopularTutorials
QuicksortAlgorithm
MergeSortAlgorithm
LinkedListDataStructure
HashTableDataStructure
DynamicProgramming
StartLearningDSA
AllDSATutorials
Python
JavaScript
C
C++
Java
Kotlin
PopularExamples
Addtwonumbers
Checkprimenumber
Findthefactorialofanumber
PrinttheFibonaccisequence
Checkleapyear
AllPythonExamples
DSAIntroduction
Whatisanalgorithm?
DataStructureandTypes
WhylearnDSA?
AsymptoticNotations
MasterTheorem
DivideandConquerAlgorithm
DataStructures(I)
Stack
Queue
TypesofQueue
CircularQueue
PriorityQueue
Deque
DataStructures(II)
LinkedList
LinkedListOperations
TypesofLinkedList
HashTable
HeapDataStructure
FibonacciHeap
DecreaseKeyandDeleteNodeOperationsonaFibonacciHeap
TreebasedDSA(I)
TreeDataStructure
TreeTraversal
BinaryTree
FullBinaryTree
PerfectBinaryTree
CompleteBinaryTree
BalancedBinaryTree
BinarySearchTree
AVLTree
TreebasedDSA(II)
BTree
InsertioninaB-tree
DeletionfromaB-tree
B+Tree
InsertiononaB+Tree
DeletionfromaB+Tree
Red-BlackTree
Red-BlackTreeInsertion
Red-BlackTreeDeletion
GraphbasedDSA
GraphDataStructure
SpanningTree
StronglyConnectedComponents
AdjacencyMatrix
AdjacencyList
DFSAlgorithm
Breadth-firstSearch
BellmanFord'sAlgorithm
SortingandSearchingAlgorithms
BubbleSort
SelectionSort
InsertionSort
MergeSort
Quicksort
CountingSort
RadixSort
BucketSort
HeapSort
ShellSort
LinearSearch
BinarySearch
GreedyAlgorithms
GreedyAlgorithm
Ford-FulkersonAlgorithm
Dijkstra'sAlgorithm
Kruskal'sAlgorithm
Prim'sAlgorithm
HuffmanCoding
DynamicProgramming
DynamicProgramming
Floyd-WarshallAlgorithm
LongestCommonSequence
OtherAlgorithms
BacktrackingAlgorithm
Rabin-KarpAlgorithm
RelatedTopics
HeapDataStructure
PriorityQueue
CompleteBinaryTree
TreeDataStructure
SortingAlgorithm
FibonacciHeap
HeapSortAlgorithm
Inthistutorial,youwilllearnabouttheheapsortalgorithmanditsimplementationinPython,Java,C,andC++.
HeapSortisapopularandefficientsortingalgorithmincomputerprogramming.Learninghowtowritetheheapsortalgorithmrequiresknowledgeoftwotypesofdatastructures-arraysandtrees.
Theinitialsetofnumbersthatwewanttosortisstoredinanarraye.g.[10,3,76,34,23,32]andaftersorting,wegetasortedarray[3,10,23,32,34,76].
Heapsortworksbyvisualizingtheelementsofthearrayasaspecialkindofcompletebinarytreecalledaheap.
Note:Asaprerequisite,youmustknowaboutacompletebinarytreeandheapdatastructure.
RelationshipbetweenArrayIndexesandTreeElements
Acompletebinarytreehasaninterestingpropertythatwecanusetofindthechildrenandparentsofanynode.
Iftheindexofanyelementinthearrayisi,theelementintheindex2i+1willbecometheleftchildandelementin2i+2indexwillbecometherightchild.Also,theparentofanyelementatindexiisgivenbythelowerboundof(i-1)/2.
RelationshipbetweenarrayandheapindicesLet'stestitout,
Leftchildof1(index0)
=elementin(2*0+1)index
=elementin1index
=12
Rightchildof1
=elementin(2*0+2)index
=elementin2index
=9
Similarly,
Leftchildof12(index1)
=elementin(2*1+1)index
=elementin3index
=5
Rightchildof12
=elementin(2*1+2)index
=elementin4index
=6
Letusalsoconfirmthattherulesholdforfindingparentofanynode
Parentof9(position2)
=(2-1)/2
=½
=0.5
~0index
=1
Parentof12(position1)
=(1-1)/2
=0index
=1
UnderstandingthismappingofarrayindexestotreepositionsiscriticaltounderstandinghowtheHeapDataStructureworksandhowitisusedtoimplementHeapSort.
WhatisHeapDataStructure?
Heapisaspecialtree-baseddatastructure.Abinarytreeissaidtofollowaheapdatastructureif
itisacompletebinarytree
Allnodesinthetreefollowthepropertythattheyaregreaterthantheirchildreni.e.thelargestelementisattherootandbothitschildrenandsmallerthantherootandsoon.Suchaheapiscalledamax-heap.Ifinstead,allnodesaresmallerthantheirchildren,itiscalledamin-heap
ThefollowingexamplediagramshowsMax-HeapandMin-Heap.
MaxHeapandMinHeapTolearnmoreaboutit,pleasevisitHeapDataStructure.
Howto"heapify"atree
Startingfromacompletebinarytree,wecanmodifyittobecomeaMax-Heapbyrunningafunctioncalledheapifyonallthenon-leafelementsoftheheap.
Sinceheapifyusesrecursion,itcanbedifficulttograsp.Solet'sfirstthinkabouthowyouwouldheapifyatreewithjustthreeelements.
heapify(array)
Root=array[0]
Largest=largest(array[0],array[2*0+1].array[2*0+2])
if(Root!=Largest)
Swap(Root,Largest)
HeapifybasecasesTheexampleaboveshowstwoscenarios-oneinwhichtherootisthelargestelementandwedon'tneedtodoanything.Andanotherinwhichtheroothadalargerelementasachildandweneededtoswaptomaintainmax-heapproperty.
Ifyou'reworkedwithrecursivealgorithmsbefore,you'veprobablyidentifiedthatthismustbethebasecase.
Nowlet'sthinkofanotherscenarioinwhichthereismorethanonelevel.
HowtoheapifyrootelementwhenitssubtreesarealreadymaxheapsThetopelementisn'tamax-heapbutallthesub-treesaremax-heaps.
Tomaintainthemax-heappropertyfortheentiretree,wewillhavetokeeppushing2downwardsuntilitreachesitscorrectposition.
Howtoheapifyrootelementwhenitssubtreesaremax-heapsThus,tomaintainthemax-heappropertyinatreewherebothsub-treesaremax-heaps,weneedtorunheapifyontherootelementrepeatedlyuntilitislargerthanitschildrenoritbecomesaleafnode.
Wecancombineboththeseconditionsinoneheapifyfunctionas
voidheapify(intarr[],intn,inti){
//Findlargestamongroot,leftchildandrightchild
intlargest=i;
intleft=2*i+1;
intright=2*i+2;
if(left
延伸文章資訊
- 1Heapsort Algorithm using min-heap - Stack Overflow
for every node i other than the root. After the heap is built, the root (leftmost position in the...
- 2Heap Sort Algorithm - Javatpoint
In this article, we will discuss the Heapsort Algorithm. Heap sort processes the elements by crea...
- 3Min Heap in Java - GeeksforGeeks
- 4Heap Sort - HackMD
What is Heap? Heap(Binary Heap) 是以tree(樹) 為基礎的資料結構, 他有以下特點: Shape Property: Heap 的資料結構永遠都是 完全二元樹C...
- 5堆積排序Heapsort
Heapsort(堆積排序)可以看作是selection sort 的變形,同樣會將資料分為sorted pile ... 將資料轉換為heap 資料結構(遞增排序用max-heap, 遞減排序...