import java.util.Scanner; import java.io.*; /* * Lab 3 * * Author: Robin Dawes * * Date: 20080922 * * Comment: This uses a large positive flag value in empty nodes of the heap. * This does not change the complexity of the algorithm. * */ public class Lab_3v2 { static int numSets; static int[] nums; static int n; static int flagValue; public static void main(String[] argv) throws Exception { Scanner myScanner = new Scanner(new File("Lab_3_Data.txt")); numSets = myScanner.nextInt(); for (int i = 0; i < numSets; i++) { n = myScanner.nextInt(); nums = new int[n]; for (int j = 0; j < n; j++) nums[j] = myScanner.nextInt(); flagValue = chooseFlag(); heapify(); for (int j = 0; j < n; j++) System.out.print(extractMin() + "\t"); System.out.println(); } } // main(String[]) static int chooseFlag() { int x = nums[0]; for (int i = 1; i < n; i++) if (nums[i] > x) x = nums[i]; return x+1; } // chooseFlag static void heapify(){ for (int i = 1; i < n; i++) { int temp = i; int tempParent = (temp - 1) / 2; while ((temp > 0) && (nums[temp] < nums[tempParent])) { swap(temp, tempParent); temp = tempParent; tempParent = (temp - 1) / 2; } // while } // for } // heapify() static void swap(int a, int b){ int t = nums[a]; nums[a] = nums[b]; nums[b] = t; } // swap(int,int) static int extractMin(){ int returnVal = nums[0]; promote(0); return returnVal; } // extractMin() static void promote(int c) { /* * This can be done iteratively, but I'm doing it recursively just for the joy of it */ if (c > n-1) return; // we have fallen off the bottom of the tree if (nums[c] == flagValue) return; // we have reached an empty node if (2*c + 1 > n - 1) { //this node is too close to the bottom of the tree to have children nums[c] = flagValue; // mark this node as empty and do nothing more } else { // at least one child is possible, so choose the smaller one int leftChild = nums[2*c + 1]; int rightChild = flagValue; if (2*c + 2 < n) rightChild = nums[2*c + 2]; // leftChild and rightChild now contain the appropriate values if there are children, // and each contains flagValue if the corresponding child is empty or non-existent if (leftChild <= rightChild) { // promote the left child nums[c] = leftChild; promote(2*c + 1); } else { // promote the right child nums[c] = rightChild; promote(2*c + 2); } } } // promote(int) } // class Lab_3v2