Question

In: Computer Science

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;

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 comparisons to 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

Solutions

Expert Solution

// BinaryTreeNode.java

public class BinaryTreeNode<T>
{
private T element;
private BinaryTreeNode<T> left, right;
  
  
BinaryTreeNode (T obj)
{
element = obj;
left = null;
right = null;
}
  
public T getValue(){
return element;
}
  
public void setValue(T element) {
this.element = element;
}
  
public BinaryTreeNode<T> getLeft() {
return left;
}
  
public void setLeft(BinaryTreeNode<T> left) {
this.left = left;
}
  
public BinaryTreeNode<T> getRight() {
return right;
}
  
public void setRight(BinaryTreeNode<T> right) {
this.right = right;
}

}

//end of BinaryTreeNode.java

// BuildTreeWithMethod.java

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

public class BuildTreeWithMethod {
  
public static void main(String[] args) throws FileNotFoundException {
  
System.out.println("Working with Integers: ");
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);
  
System.out.println("\nWorking with Strings: ");
String filename = "words2.txt";
// open file
Scanner fileScan = new Scanner(new File(filename));
String word;
  
// create root node and set it to null
BinaryTreeNode<String> rootStr = null;
  
// loop to read till the end of file word by word
while(fileScan.hasNext())
{
word = fileScan.next(); // read a word
  
// rootStr not set, initialize it with the word read
if(rootStr == null)
rootStr = new BinaryTreeNode<String>(word);
else // rootStr initialized, insert word in tree with root as rootStr
TreeInsert(rootStr, word);
}
  
fileScan.close(); // close the file

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

// re-open the file to calculate total comparisons
fileScan = new Scanner(new File(filename));
totalComparisons=0;

int totalElements = 0;

// read till the end of file word by word, calculating total comparisons
while(fileScan.hasNext())
{
word = fileScan.next();

totalElements++;
totalComparisons=totalComparisons + Comparisons(rootStr, word);
  
}
  
fileScan.close(); // close the file

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/totalElements);

  
}
  
//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();
}
}
  
}
}
  
// method to return number of comparison to search for target
public static int Comparisons(BinaryTreeNode root, int target)
{
// set curr to root of tree
BinaryTreeNode curr = root;
int numComparison = 0; // initialize the numComparison to 0
  
// loop over the tree
while(curr != null)
{
// increment numComparison
numComparison++;
// get the current value
int currValue= (int)curr.getValue();
if(target == currValue) // target found, exit the loop
break;
else if(target > currValue) // target > currValue, search for target in right subtree
curr = curr.getRight();
else // target < currValue, search for target in left subtree
curr = curr.getLeft();
}
  
return numComparison;
}
  
//method to insert a string (str) into a non-null BST tree
public static void TreeInsert(BinaryTreeNode root, String str)
{
BinaryTreeNode b=new BinaryTreeNode(str);
BinaryTreeNode curr=root;
  
while (curr != null) {
String currValue= (String)curr.getValue();
  
if(str.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();
}
}
}
}
  
// method to return number of comparison to search for target
public static int Comparisons(BinaryTreeNode root, String target)
{
// set curr to root of tree
BinaryTreeNode curr = root;
int numComparison = 0; // initialize numComparison to 0
  
// loop over the tree
while(curr != null)
{
numComparison++; // increment numComparison
// get the current value
String currValue= (String)curr.getValue();
  
if(target.equals(currValue)) // target found, exit the loop
break;
else if(target.compareTo(currValue) > 0) // target > currValue, search in right subtree
curr = curr.getRight();
else // target < currValue, search in left subtree
curr = curr.getLeft();
}
  
return numComparison;
}
}

// end of BuildTreeWithMethod.java

Output:

Input file: words2.txt

Output :

Feel free to contact me if you have any queries.

Thank you :)


Related Solutions

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:...
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 program in C++ to find the number of comparisons using binarySearch and the sequential...
Write a program in C++ to find the number of comparisons using binarySearch and the sequential search algorithm as follows: Suppose list is an array of 1000 elements. a. Use a random number generator to fill list. b. Use any sorting algorithm to sort list. c. Search list for some items as follows: i. 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.)...
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...
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.)...
Write a method called mode that returns the most frequently occurring element of an array of...
Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at least one element and that every element in the array has a value between 0 and 100 inclusive. Break ties by choosing the lower value. For example, if the array passed contains the values [27, 15, 15, 11, 27], your method should return 15. write a version of this method that does not rely on the values...
Write recursive method to return true if a given array has element equal to employee emp,...
Write recursive method to return true if a given array has element equal to employee emp, or returns false otherwise. Array can be empty or not. //PRECONDITION: Varible n denotes the number of occupied positions in the array and must be non-negative. Employee class has method getSalary() that returns employee's salary, // and it has method boolean equals(Employee emp) that accept an employee object and returns true if employee calling the equals method is equal as employee emp, and returns...
As code is given below, follow the instructions: 1. Count the number of comparisons and find...
As code is given below, follow the instructions: 1. Count the number of comparisons and find where to put that counter in the code 2. Pick a random pivot, right pivot, left pivot, middle pivot for each smaller array /sub-array import java.util.*; import java.util.List; public class QuickSort { public static void main(String[] args) { int[] values = { 6, 5, 4, 3, 1, 7, 8 }; System.out.println("Original order: "); for (int element : values) System.out.print(element + " "); IntQuickSorter.quickSort(values); System.out.println("\nFirst...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT