Import java. util .*; Public class HeapSort { Public static void main (String [] args ){ Int arr [] = {20, 40, 30, 10, 90, 70}; // original array Heapsort (arr, arr. length); // sort the heap. System. out. println (Arrays. toString (arr); // Print the sorted array } Public static void heapsort (int heap [], int n ){ // N indicates that heap [] has multiple fewer elements. // Array heap indicates the heap from index 0 to lastIndex For (int rootIndex = n/2-1; rootIndex> = 0; rootIndex --) {// The node at the index rootIndex is the root of the half heap. Reheap (heap, rootIndex, n-1); // rebuild heap and sort System. out. println (Arrays. toString (heap) + "for1"); // tracks array changes } Swap (heap, 0, n-1); // place the largest element to the end, so that the node can be ignored after the sorting continues. System. out. println (Arrays. toString (heap) + "swap "); // Gradually delete the heap size For (int lastIndex = n-2; lastIndex> = 0; lastIndex --){// Reheap (heap, 0, lastIndex); // rebuild heap and sort System. out. println (Arrays. toString (heap) + "for"); // tracks array changes Swap (heap, 0, lastIndex); // exchange System. out. println (Arrays. toString (heap) + "swap2"); // tracks array changes }
} Private static void reheap (int heap [], int BrootIndex, int BlastIndex ){ // The node at the index BrootIndex is the root of the half heap Boolean done = false; Int tmp = heap [BrootIndex]; // Save the value of the half-heap root to the temporary variable tmp. Int leftChildIndex = 2 * BrootIndex + 1; // left subnode of the half heap root // Int counter = 0 counts the number of while executions; While (! Done & (leftChildIndex <= BlastIndex) {// Determine whether the root node of g semi-heap has a left sub-node by checking whether the left sub-node index is greater than the BlastIndex. Int largerChildIndex = leftChildIndex ;// Int rightChildIndex = leftChildIndex + 1; // The right subnode of the half heap root // Determine whether the half-heap Root has the right subnode If (rightChildIndex <= BlastIndex) & (heap [rightChildIndex]> heap [largerChildIndex]) { LargerChildIndex = rightChildIndex; }
If (tmp // Give the value of the left subnode to the half-heap root node Heap [BrootIndex] = heap [largerChildIndex]; // In addition to the values of the left subnode and the root node, the indexes of the subnode are also exchanged. BrootIndex = largerChildIndex; LeftChildIndex = 2 * BrootIndex + 1; // System. out. println ("trace the value of BrootIndex in if:" + BrootIndex );// } Else Done = true; // key: Use done to determine whether a half heap has been converted to a heap. // Counter ++; count the number of while executions } // Give the root value of the half heap to the New Left subnode. Heap [BrootIndex] = tmp; // System. out. println (Arrays. toString (heap) + "while"); // tracks array changes } Public static void swap (int heap [], int a, int n ){ Int temp; Temp = heap [a]; Heap [a] = heap [n]; Heap [n] = temp;
} } |