Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please help me implement Package comp2011.ass2; import java.util.Arrays; /** * * * Use a maximum tree to sort an array. */ public class MaxTree {

Please help me implement

Package comp2011.ass2; import java.util.Arrays; /** * * * Use a maximum tree to sort an array. */ public class MaxTree { private class Node { int element; public Node leftChild, rightChild; public Node(int element) { this.element = element; } public String toString() { return String.valueOf(element); } } Node root; // Build a maximum tree out of an array. public MaxTree(int[] a) { int n = a.length; Node[] nodes = new Node[n]; for (int i = 0; i < n; i++) { nodes[i] = new Node(a[i]); } while (n > 1) { for (int i = 0; i < n / 2; i++) { int max = Math.max(nodes[i * 2].element, nodes[i * 2 + 1].element); Node newNode = new Node(max); newNode.leftChild = nodes[i * 2]; newNode.rightChild = nodes[i * 2 + 1]; nodes[i] = newNode; // why it's safe to resue the space? } // n might be odd. if (n % 2 != 0) { nodes[n/2] = new Node(nodes[n - 1].element); nodes[n/2].leftChild = nodes[n - 1]; } n = (n + 1) / 2; } root = nodes[0]; } // imlement this // The running time of deleteMax is O( ). public int deleteMax() { return 0; } public static void treeSort(int[] a) { MaxTree tree = new MaxTree(a); for (int i = a.length; i > 0 ; i--) { a[i - 1] = tree.deleteMax(); } } public static void main(String[] args) { // int size = 10; // int[] a = new int[size]; // SecureRandom random = new SecureRandom(); // for (int i = 0; i < size; i++) // a[i] = random.nextInt(size); int[] a = {3, 2, 6, 13, 8, 4, 10, 7, 14, 11, 12, 5, 9}; System.out.println(Arrays.toString(a)); treeSort(a); System.out.println(Arrays.toString(a)); } } 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Programming questions

Question

What was the primary goal of the woman suffrage movement?

Answered: 1 week ago