Sorting algorithms/Heapsort: Difference between revisions

m (→‎{{header|Ring}}: Remove vanity tags)
Line 1,990:
<pre>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
</pre>
 
 
=={{header|Julia}}==
<lang julia>function percolate_down!(a, first, last)
r = first
while 2 * r + 1 <= last
c = 2 * r + 1
if c + 1 <= last && a[c + 1] < a[c + 2]
c += 1
end
if a[r + 1] < a[c + 1]
a[c + 1], a[r + 1] = a[r + 1], a[c + 1]
r = c
else
break
end
end
end
function heapify!(a, n)
first = div(n - 2, 2)
while first >= 0
percolate_down!(a, first, n - 1)
first -= 1
end
end
 
function heapsort(a)
n = length(a)
heapify!(a, n)
last = n - 1
while last > 0
a[1], a[last + 1] = a[last + 1], a[1]
last -= 1
percolate_down!(a, 0, last)
end
a
end
 
a = shuffle(collect(1:12))
println("Unsorted: $a")
println("Heap sorted: ", heapsort(a))
</lang>{{output}}<pre>
Unsorted: [3, 12, 11, 4, 2, 7, 5, 8, 9, 1, 10, 6]
Heap sorted: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</pre>
 
4,105

edits