Sorting algorithms/Heapsort: Difference between revisions

The code was completely unreadable for anyone want to find out what Heapsort does and how it works in groovy. This code should be much better to read. It is a adaption of the same code in JAVA example here.
imported>SerErris
(The code was completely unreadable for anyone want to find out what Heapsort does and how it works in groovy. This code should be much better to read. It is a adaption of the same code in JAVA example here.)
Line 2,892:
 
=={{header|Groovy}}==
Translated from JAVA code:
Loose translation of the pseudocode:
<syntaxhighlight lang="groovy">def makeSwap = { heapify(a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] } count){
//start is assigned the index in a of the last parent node
def start = (count - 2).intdiv(2) //binary heap
 
while(start >= 0){
def checkSwap = { list, i, j = i+1 -> [(list[i] > list[j])].find{ it }.each { makeSwap(list, i, j) } }
//sift down the node at index start to the proper place
 
//such that all nodes below the start index are in heap
def siftDown = { a, start, end ->
def p = start //order
while siftDown(p*2a, <start, end)count {- 1)
start--
def c = p*2 + ((p*2 + 1 < end && a[p*2 + 2] > a[p*2 + 1]) ? 2 : 1)
if (checkSwap(a, c, p)) { p = c }
else { return }
}
//after sifting down the root all nodes/elements are in heap order
}
 
def heapifysiftDown(a, =start, end){
//end represents the limit of how far down the heap to sift
(((it.size()-2).intdiv(2))..0).each { start -> siftDown(it, start, it.size()-1) }
def root = start;
 
while((root * 2 + 1) <= end){ //While the root has at least one child
int child = root * 2 + 1 //root*2+1 points to the left child
//if the child has a sibling and the child's value is less than its sibling's...
def c = p*2 + (if(p*2child + 1 <= end && a[p*2 + 2child] >< a[p*2child + 1]) ? 2 : 1)
child = child + 1 //... then point to the right child instead
if(a[root] < a[child]){ //out of max-heap order
int tmp = a[root] //exchange root and child
a[root] = a[child]
a[child] = tmp
root = child //repeat to continue sifting down the child now
}else
else { return };
list}
}
 
def heapSort = (a){ list ->
heapifydef count = a.size(list)
 
(0..<(list.size())).reverse().each { end ->
//first place a in max-heap order
makeSwap(list, 0, end)
siftDownheapify(list, 0a, end-1count)
 
def end = count - 1
while(end > 0){
//swap the root(maximum value) of the heap with the
//last element of the heap
def tmp = a[end]
a[end] = a[0]
a[0] = tmp
//put the heap back in max-heap order
makeSwapsiftDown(lista, 0, end - 1)
//decrement the size of the heap so that the previous
//max value will stay in its proper place
end--
}
 
list
return a
}</syntaxhighlight>
Test:
Anonymous user