Anonymous user
Sorting algorithms/Heapsort: Difference between revisions
m
→{{header|Java}}: Rm extra tabs
(Added Java) |
m (→{{header|Java}}: Rm extra tabs) |
||
Line 252:
Direct translation of the pseudocode.
<lang java>public static void heapSort(int[] a){
//first place a in max-heap order▼
heapify(a, count);▼
int end = count - 1;▼
while(end > 0){▼
//swap the root(maximum value) of the heap with the▼
//last element of the heap▼
int tmp = a[end];▼
a[end] = a[0];▼
a[0] = tmp;▼
//decrement the size of the heap so that the previous▼
}▼
//max value will stay in its proper place
end--;
}
}
//after sifting down the root all nodes/elements are in heap order▼
}
}
▲ }else
}
▲ 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...
▲ if(child + 1 <= end && a[child] < a[child + 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];
▲ a[child] = tmp;
▲ root = child; //repeat to continue sifting down the child now
▲ return;
▲ }</lang>
=={{header|OCaml}}==
<lang ocaml>let heapsort a =
|