Heap Sort
Package Sort;public class Heap_sort {public static void main (string[] args) {//TODO auto-generated method stub heap_sort qs = new Heap_sort (); int[] Arr = {10,9,8,7,6,5,4,3,2,1};qs.heapsort (arr); for (int i=0;i<arr.length;i++) {System.out.println (Arr[i]) ;}} Adjust function public void Headadjust (int[] elements,int pos,int len) {//Save the current node value int swap = Elements[pos]; Navigates to the left side of the current node int child = pos * 2 + 1; Recursive until there are no children (Child < Len) {//If the current node has a child node on the right and a larger right child node, the right child node and the current node are compared if (children + 1 < len && Elements[child] < Elements[child + 1]) {child + = 1; }//compares the current node and the largest child node, which is less than the value exchange, after which the current node is positioned on the child node if (Elements[pos] < Elements[child]) {Elements[pos] = Elements[child]; pos = child; Child = pos * 2 + 1; } else{break; } Elements[pos] = swap; }}//Build heap public void buildheap (int[] elements) {//start with the last node that has child nodes, compare the node with its child nodes,//exchange the maximum numberWith the node, after the interchange, then the forward node in turn is processed in the same interchange,//until a large top heap (ascending to a large top, descending to a small top) for (int i=elements.length/2; i>=0; i--) {headadjust ( Elements, I, elements.length); }} public void Heapsort (int[] elements) {//Build heap buildheap (elements); From the tail of the sequence to adjust for (int i=elements.length-1; i>0; i--) {//heap top is always the largest element, therefore, the top and tail elements of the heap are exchanged, the//maximum elements are saved at the tail, and do not participate in the //alert (elements) of the face adjustment; int swap = Elements[i]; Elements[i] = elements[0]; Elements[0] = swap; alert (elements); Adjust the maximum element to the top of the heap headadjust (elements, 0, i); alert (elements); } }}
Java sorting algorithm--Heap ordering