Question

In: Computer Science

In JAVA!!! write a method called Comparisons that will return the number of comparisons to find...

In JAVA!!!

write a method called Comparisons that will return the number of comparisons to find an element in the tree. The main program calls this method for each element, adding the comparisons each time in order to count the total number of comparisons. The program then outputs the total number of comparisons and the average number. You may use the program BuildTreeWIthMethod to build your tree. Then, after you have made the call to inOrder(root), add the following code:

int totalComparisons=0;

for (int i = 0; i < arr.length; i++) {
totalComparisons=totalComparisons + Comparisons(root, arr[i]);
}

System.out.println("Number of comparisons to find all data in tree is " + totalComparisons);
System.out.println("Average number of comparisons is " + totalComparisons*1.0/arr.length);

To be clear: you ONLY have to write the method and to put the code above into your program - use the program I gave to you.

2. Repeat the above for strings in an input file. The input file is here. words2.txt

In each case work the tree by hand (pencil and paper) so you know what the answer should be. You can EITHER submit two programs OR put both into one program. Your choice.

FOR THIS LAB it is OK if you have to write two TreeInsert methods (one for Integer, one for Strings), and two Comparisons methods (you can write template methods in the next lab) - but if you put template methods in here that is good too. ALSO the integers are in an array, but the Strings are in a file. So after you have built a tree of Strings you either have to close the input file, then reopen it and pick up each word again and calculate the number of comparisonsto find it, or you have to look for another solution. (Possibilities are to read them into an array at the beginning before building your tree or count comparisons in the same loop where you read in your string. Either is fine (for now)).

words2.txt

Hi

Bye

Monday

April

Donkey

Yellow

Computers

Monkey

Dog

Cat

BuildTreeWithMethod

public class BuildTreeWithMethod {

public static void main(String[] args) {
  
Integer[] arr = {6, 8, 3, 4, 9, 2 }; //data to put in BST
  
BinaryTreeNode<Integer> root=new BinaryTreeNode<Integer>(arr[0]);//the root

//build the tree
for (int i = 1; i < arr.length; i++) {
  
TreeInsert(root, arr[i]);

}
//print out the data - should be sorted
inOrder(root);

}
//method to perform- an inorder traversal of a BST
public static void inOrder(BinaryTreeNode t) {
if (t != null)
{
inOrder(t.getLeft());
System.out.println(t.getValue());
inOrder(t.getRight());

}
}
  
//method to insert an integer (num) into a non-null BST tree
public static void TreeInsert(BinaryTreeNode root, Integer num)
{ BinaryTreeNode b=new BinaryTreeNode(num);
BinaryTreeNode curr=root;
while (curr != null) {
int currValue= (int)curr.getValue();
if(num<currValue){
if (curr.getLeft() == null) {
curr.setLeft(b);
  
break;
} else {
curr = curr.getLeft();
  
}

} else {
if (curr.getRight() == null) {
curr.setRight(b);

break;
} else {
curr = curr.getRight();

}
}
}
  

}
  
}

Solutions

Expert Solution


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;


public class BuildTreeWithMethod {

        public static void main(String[] args) throws FileNotFoundException {

                Integer[] arr = {6, 8, 3, 4, 9, 2 }; //data to put in BST

                BinaryTreeNode<Integer> root=new BinaryTreeNode<Integer>(arr[0]);//the root

                //build the tree
                for (int i = 1; i < arr.length; i++) {
                        TreeInsert(root, arr[i]);
                }
                //print out the data - should be sorted
                inOrder(root);

                int totalComparisons=0;

                for (int i = 0; i < arr.length; i++) {
                        totalComparisons=totalComparisons + Comparisons(root, arr[i]);
                }
        System.out.println("Number of comparisons to find all data in tree is " + totalComparisons);
                System.out.println("Average number of comparisons is " + totalComparisons*1.0/arr.length);

                List<String> s = new ArrayList<>(); //String arraylist

                //Scanning input from file
                File file = new File("words2.txt"); //Enter the file location
                Scanner sc = new Scanner(file); 
                while (sc.hasNextLine()) 
                        s.add(sc.nextLine());

                BinaryTreeNode<String> p = new BinaryTreeNode<String>(s.get(0));
                //String Binary Tree Node

                for (int i = 1; i < s.size(); i++) {
                        TreeInsert(p, s.get(i));
                }

                totalComparisons = 0;

                for (int i = 0; i < s.size(); i++) {
                        totalComparisons=totalComparisons + Comparisons(p, s.get(i));
                        //System.out.println(totalComparisons);
                }

                System.out.println("Number of comparisons to find all data in tree is " + totalComparisons);
                System.out.println("Average number of comparisons is " + totalComparisons*1.0/s.size());

        }

        //method to perform- an inorder traversal of a BST
        public static void inOrder(BinaryTreeNode t) {
                if (t != null)
                {
                        inOrder(t.getLeft());
                        System.out.println(t.getValue());
                        inOrder(t.getRight());

                }
        }

        //Comparison method for Integer
        public static int Comparisons(BinaryTreeNode<Integer> root, int toFind)
        {       
                int count=1;
                BinaryTreeNode<Integer> node=root;

                //check whether the value of node is equal to toFind
                while(!(node.getValue().intValue()==toFind))
                {
                        if(node.getValue().intValue()>toFind) {
                                node = node.getLeft();
                                count++;
                        }
                        else {
                                node = node.getRight();
                                count++;
                        }
                }
                return count;
        }

        //Comparison method for String
        public static int Comparisons(BinaryTreeNode<String> root, String toFind)
        {       
                int count=1;
                BinaryTreeNode<String> node=root;

                //check whether the value of node is equal to toFind
                while(!node.getValue().equals(toFind))
                {
                        if(node.getValue().compareTo(toFind)>0) {
                                node = node.getLeft();
                                count++;
                        }
                        else {
                                node = node.getRight();
                                count++;
                        }
                }
                return count;
        }



        //method to insert an integer (num) into a non-null BST tree
        public static void TreeInsert(BinaryTreeNode<Integer> root, Integer num)
        {
                BinaryTreeNode b=new BinaryTreeNode(num);
                BinaryTreeNode curr=root;
                while (curr != null) {
                        int currValue= (int)curr.getValue();
                        if(num<currValue){
                                if (curr.getLeft() == null) {
                                        curr.setLeft(b);
                                        break;
                                } else {
                                        curr = curr.getLeft();
                                }

                        } else {
                                if (curr.getRight() == null) {
                                        curr.setRight(b);
                                        break;
                                } else {
                                        curr = curr.getRight();
                                }
                        }
                }


        }

        //method to insert an String into a non-null BST tree
        public static void TreeInsert(BinaryTreeNode<String> root, String num)
        { 
                BinaryTreeNode<String> b= new BinaryTreeNode(num);
                BinaryTreeNode<String> curr=root;
                while (curr != null) {
                        String currValue = curr.getValue();
                        if(num.compareTo(currValue)<0){
                                if (curr.getLeft() == null) {
                                        curr.setLeft(b);
                                        break;
                                } else {
                                        curr = curr.getLeft();
                                }

                        } else {
                                if (curr.getRight() == null) {
                                        curr.setRight(b);
                                        break;
                                } else {
                                        curr = curr.getRight();
                                }
                        }
                }
        }
}

output:


Related Solutions

write a method called Comparisons that will return the number of comparisons to find an element...
write a method called Comparisons that will return the number of comparisons to find an element in the tree. The main program calls this method for each element, adding the comparisons each time in order to count the total number of comparisons. The program then outputs the total number of comparisons and the average number. You may use the program BuildTreeWIthMethod to build your tree. Then, after you have made the call to inOrder(root), add the following code: int totalComparisons=0;...
IN C++ Write a program to find the number of comparisons using binarySearch and the sequential...
IN C++ Write a program to find the number of comparisons using binarySearch and the sequential search algorithm as follows: Suppose list is an array of 1000 elements. 3 Search list for some items as follows: a. Use the binary search algorithm to search the list. (You may need to modify the algorithm given in this chapter to count the number of comparisons.) b. Use the binary search algorithm to search the list, switching to a sequentialsearch when the size...
IN C++ Write a program to find the number of comparisons using binarySearch and the sequential...
IN C++ Write a program to find the number of comparisons using binarySearch and the sequential search algorithm as follows: Suppose list is an array of 1000 elements. 2 Use any sorting algorithm to sort list.
In C++ Write a program to find the number of comparisons using binarySearch and the sequential...
In C++ Write a program to find the number of comparisons using binarySearch and the sequential search algorithm as follows: Suppose list is an array of 1000 elements. 5.1 Use a random number generator to fill list.
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called...
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called without instantiating the class and returns a random Date between Jan 1, 2000 and Dec 31, 2010.
Question 5 Write a program to find the number of comparisons using binarySearch and the sequential...
Question 5 Write a program to find the number of comparisons using binarySearch and the sequential search algorithm as follows: Suppose list is an array of 1000 elements. 5.1 Use a random number generator to fill list. 5.2 Use any sorting algorithm to sort list. 5.3 Search list for some items as follows: a. Use the binary search algorithm to search the list. (You may need to modify the algorithm given in this chapter to count the number of comparisons.)...
In Java: Write a method called copy, which is passed A[], which is an array of...
In Java: Write a method called copy, which is passed A[], which is an array of int, and an integer n. The method returns a new array consisting of the first n items in A[]. Write a method called slice, which is passed A[], which is an array of int, an integer i and an integer j. The method returns a new array consisting of all of the items in A from A[i] to A[j] inclusive.
Write a method in JAVA, called binarySearch, that returns the index of the key element if...
Write a method in JAVA, called binarySearch, that returns the index of the key element if found in the array, otherwise it will return the value of minus(insertion point +1). In main, use an initializer list create an array of ints called nums holding the following values: 1, 4, 13, 43, -25, 17, 22, -37, 29. Test your binarySearch method on nums with a key value number in it (e.g. 4) and one that is not (e.g. 100). Ex. Given...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a counter and then increments the number of seconds. The counter will start at 00:00 and each time the number of seconds reaches 60, minutes will be incremented. You will not need to implement hours or a sleep function, but if minutes or seconds is less than 10, make sure a leading zero is put to the left of the number. For example, 60 seconds:...
use java for : 1. Write a method called indexOfMax that takes an array of integers...
use java for : 1. Write a method called indexOfMax that takes an array of integers and returns the index of the largest element. 2. The Sieve of Eratosthenes is “a simple, ancient algorithm for finding all prime numbers up to any given limit” (https://en.wikipedia. org/wiki/Sieve_of_Eratosthenes).Write a method called sieve that takes an integer parameter, n, and returns a boolean array that indicates, for each number from 0 to n -1, whether the number is prime.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT