Sorting algorithms/Heapsort: Difference between revisions
Content added Content deleted
Not a robot (talk | contribs) (Add PL/M) |
(Replace translated implementation with native implementation of pseudocode from the introduction) |
||
Line 2,718: | Line 2,718: | ||
=={{header|Javascript}}== |
=={{header|Javascript}}== |
||
{{trans|CoffeeScript}} |
|||
<lang Javascript> |
<lang Javascript> |
||
function |
function heapSort(arr) { |
||
heapify(arr) |
|||
var tmp = data[i]; |
|||
end = arr.length - 1 |
|||
while (end > 0) { |
|||
[arr[end], arr[0]] = [arr[0], arr[end]] |
|||
} |
|||
⚫ | |||
⚫ | |||
function heap_sort(arr) { |
|||
put_array_in_heap_order(arr); |
|||
⚫ | |||
while(end > 0) { |
|||
⚫ | |||
sift_element_down_heap(arr, 0, end); |
|||
⚫ | |||
} |
} |
||
} |
} |
||
function |
function heapify(arr) { |
||
⚫ | |||
⚫ | |||
i = arr.length / 2 - 1; |
|||
while (start >= 0) { |
|||
⚫ | |||
while (i >= 0) { |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
} |
} |
||
function |
function siftDown(arr, startPos, endPos) { |
||
let rootPos = startPos |
|||
while(i < max) { |
|||
while (rootPos * 2 + 1 <= endPos) { |
|||
childPos = rootPos * 2 + 1 |
|||
if (childPos + 1 <= endPos && arr[childPos] < arr[childPos + 1]) { |
|||
childPos++ |
|||
} |
|||
if ( |
if (arr[rootPos] < arr[childPos]) { |
||
[arr[rootPos], arr[childPos]] = [arr[childPos], arr[rootPos]] |
|||
rootPos = childPos |
|||
} else { |
|||
return |
|||
⚫ | |||
} |
} |
||
} |
} |
||
test('rosettacode', () => { |
|||
arr = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8,] |
arr = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8,] |
||
heapSort(arr) |
|||
expect(arr).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) |
|||
})</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |