Question

The following problem was done using Java. Question: Design, code, and test a program that implements...

The following problem was done using Java.

Question: Design, code, and test a program that implements an optimal Huffman algorithm with a time complexity of O(n log2n), n being the number of code symbols).

My code keeps giving me errors. Please post code and solution.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE

import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Comparator;

// node class is the basic structure
// of each node present in the Huffman - tree.
class HuffmanNode {

   int data;
   char c;

   HuffmanNode left;
   HuffmanNode right;
}

// comparator class helps to compare the node
// on the basis of one of its attribute.
// Here we will be compared
// on the basis of data values of the nodes.
class MyComparator implements Comparator<HuffmanNode> {
   public int compare(HuffmanNode x, HuffmanNode y)
   {
       return x.data - y.data;
   }
}

public class Huffman {

   // recursive function to print the
   // huffman-code through the tree traversal.
   // Here s is the huffman - code generated.
   public static void printCode(HuffmanNode root, String s)
   {

       // base case; if the left and right are null
       // then its a leaf node and we print
       // the code s generated by traversing the tree.
       if (root.left == null && root.right == null && Character.isLetter(root.c)) {
// c is the character in the node
           System.out.println(root.c + ":" + s);

           return;
       }

       // if we go to left then add "0" to the code.
       // if we go to the right add"1" to the code.

       // recursive calls for left and
       // right sub-tree of the generated tree.
       printCode(root.left, s + "0");
       printCode(root.right, s + "1");
   }

   // main function
   public static void main(String[] args)
   {

       Scanner s = new Scanner(System.in);

       // number of characters.
       int n = 6;
       char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
       int[] charfreq = { 5, 9, 12, 13, 16, 45 };

       // creating a priority queue q.
       // makes a min-priority queue(min-heap).
       PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator());

       for (int i = 0; i < n; i++) {

           // creating a Huffman node object
           // and add it to the priority queue.
           HuffmanNode hn = new HuffmanNode();

           hn.c = charArray[i];
           hn.data = charfreq[i];

           hn.left = null;
           hn.right = null;

           // add functions adds
           // the huffman node to the queue.
           q.add(hn);
       }

       // create a root node
       HuffmanNode root = null;

       // Here we will extract the two minimum value
       // from the heap each time until
       // its size reduces to 1, extract until
       // all the nodes are extracted.
       while (q.size() > 1) {

           // first min extract.
           HuffmanNode x = q.peek();
           q.poll();

           // second min extarct.
           HuffmanNode y = q.peek();
           q.poll();

           // new node f which is equal
           HuffmanNode f = new HuffmanNode();

           // to the sum of the frequency of the two nodes
           // assigning values to the f node.
           f.data = x.data + y.data;
           f.c = '-';

           // first extracted node as left child.
           f.left = x;

           // second extracted node as the right child.
           f.right = y;

           // marking the f node as the root node.
           root = f;

           // add this node to the priority-queue.
           q.add(f);
       }

       // print the codes by traversing the tree
       printCode(root, "");
   }
}

OUTPUT

Time complexity:
O(nlogn) where n is the number of unique characters.
If there are n nodes, extractMin() is called 2*(n – 1) times. extractMin() takes O(logn) time as it calles minHeapify().
So, overall complexity is O(nlogn).

Add a comment
Know the answer?
Add Answer to:
The following problem was done using Java. Question: Design, code, and test a program that implements...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 1) A Java program that implements an insertion sort algorithm. (InsertionSort.java): Must include the proper comments...

    1) A Java program that implements an insertion sort algorithm. (InsertionSort.java): Must include the proper comments in the code. 2) A report in pdf. It contains: a) the pseudocode of the insertion sort algorithm and assertions between lines of the algorithm. b) As insertion sort has a nested-loop of two layers, you need to put one assertion in each loop. c) a proof of the partial correctness of the algorithm using mathematical induction c.1) prove the correctness of the two...

  • in JAVA program.Use top-down design to design and implement a program to ask the user to...

    in JAVA program.Use top-down design to design and implement a program to ask the user to enter a list of integers, and then display to the user the mean and median of this list. You should first prompt the user to specify the length of the list of integers. For this assignment, your code should create an array of size 10, and then allow the user to specify the number of integers in their list, up to a maximum of...

  • Design an algorithm for the following description. Solution can be done in pseudo-code or steps of...

    Design an algorithm for the following description. Solution can be done in pseudo-code or steps of the algorithm. Describe and analyze an algorithm that takes an unsorted array A of n integers (in an unbounded range) and an integer k, and divides A into k equal-sized groups, such that the integers in the first group are lower than the integers in the second group, and the integers in the second group are lower than the integers in the third group,...

  • Task Algorithms: Pattern Matching (in java) Write a program that gets two strings from user, size...

    Task Algorithms: Pattern Matching (in java) Write a program that gets two strings from user, size and pattern, and checks if pattern exists inside size, if it exists then program returns index of first character of pattern inside size, otherwise it returns -1. The method should not use built-in methods such as indexOf , find, etc. Only charAt and length are allowed to use. Analyze the time complexity of your algorithm. Your solution is not allowed to be> = O...

  • Java question Given an array of integer numbers, write a linear running time complexity program in...

    Java question Given an array of integer numbers, write a linear running time complexity program in Java to find the stability index in the given input array. For an array A consisting n integers elements, index i is a stability index in A itf ATO] + A[1] + +A[iI-1] Ali+1]+ Ali+2] +... + A[n-1]; where 0 <i< n-1 Similarly, 0 is an stability index if (A[1] A[2]A[n-1]) 0 and n-1 is an stability index if (A[0] A[1]+... A[n-21) 0 Example:...

  • In the following graph, write a Java program using Topological Sort. please write java code and...

    In the following graph, write a Java program using Topological Sort. please write java code and show me the output. Thank you :) b.

  • Stacks and Java 1. Using Java design and implement a stack on an array. Implement the...

    Stacks and Java 1. Using Java design and implement a stack on an array. Implement the following operations: push, pop, top, size, isEmpty. Make sure that your program checks whether the stack is full in the push operation, and whether the stack is empty in the pop operation. None of the built-in classes/methods/functions of Java can be used and must be user implemented. Practical application 1: Arithmetic operations. (a) Design an algorithm that takes a string, which represents an arithmetic...

  • Instructions Write a program in Java that implements the A* algorithm to find a path from...

    Instructions Write a program in Java that implements the A* algorithm to find a path from any two given nodes. Problem Overview & Algorithm Description In a fully-observable environment where there are both pathable and blocked nodes, an agent must find a good path from their starting node to the goal node. The agent must use the A* algorithm to determine its path. For this program, you must use the Manhattan method for calculating the heuristic. Remember: your heuristic function...

  • Given an array of integer numbers, write a linear running time complexity program in Java to...

    Given an array of integer numbers, write a linear running time complexity program in Java to find the stability index in the given input array. For an array A consisting n integers elements, index i is a stability index in A if A[0] + A[1] + ... + A[i-1] = A[i+1] + A[i+2] + ... + A[n-1]; where 0 < i < n-1. Similarly, 0 is an stability index if (A[1] + A[2] + ... + A[n-1]) = 0 and...

  • Using Java, please design the GUI in the following prompt. PLEASE TEST YOUR PROGRAM. Thanks! Write...

    Using Java, please design the GUI in the following prompt. PLEASE TEST YOUR PROGRAM. Thanks! Write a program that displays three buttons with the names or images of three candidates for public of office. Imagine that a person votes by clicking the button that shows the candidate of his/her choice. Display the current number of votes above each button. Include a Finished button that erases the images of the losers and displays only the winner's image with a message of...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT