SlideShare a Scribd company logo
1 of 16
Download to read offline
(In java language)
1. Use recursion in implementing the binarySearch method
2. Use Generics in implementing different methods
3. Use the attached driver. Do not modify the driver
Please put answers into the skeleton / complete the following given skeleton with the code in
java language:
import java.util.ArrayList;
public class MyGenerics{
//Declarations
//****************************************************************************
//No-argument constructor:
//****************************************************************************
public MyGenerics (){
}//end of constructor
//****************************************************************************
//max: Receives a generic one-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[] list){
return null;
}//end of max
//****************************************************************************
//max: Receives a generic two-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[][] list) {
return null;
}
//****************************************************************************
//largest: Receives a generic arrayList and returns the maximum
// value in the array.
//****************************************************************************
public > E largest(ArrayList list) {
return null;
}
//****************************************************************************
//binarySearch: Receives a generic one-dimensional array and a generic key
// and returns the location of the key (positive) or
// a negative location if not found.
//****************************************************************************
public > int binarySearch(E[] list, E key) {
int low = 0;
int high = list.length - 1;
return binarySearch (list, key, low, high);
}
public > int binarySearch(E[] list, E key, int low, int high) {
return -99; // update
}
//****************************************************************************
//sort: Receives a generic arrayList and returns nothing.
//****************************************************************************
public > void sort(ArrayList list) {
}
//****************************************************************************
//sort: Receives a generic one-dimensional array and returns nothing.
//****************************************************************************
public > void sort(E[] list) {
}
//****************************************************************************
//displayOneDList: Receives a generic one-dimensional array and displays its contents
//****************************************************************************
public void displayOneDList(E[] list, String listName){
}
//****************************************************************************
//displayTwoDList: Receives a generic two-dimensional array & a string name
// and displays its contents
//****************************************************************************
public void displayTwoDList(E[][] list, String listName){
}
//****************************************************************************
//displayArrayList: Receives a generic arraylist & a string name
// and displays its contents
//****************************************************************************
public void displayArrayList(ArrayList list, String listName){
}
}
******************* This is the tester for the given skeleton******************
import java.util.*;
public class MyGenerics_Tester{
//Declrations
public static void main (String [] args){
//Declarations
Integer [] intList = {4, 7, 2, 20, 30, 22};
Double [] doubleList = {4.0, 7.5, 2.3, 20.7, 30.1, 22.8};
String [] stringList = {"Tony","Paige","Denzel","Travis","Austin","Thomas",
"Demetrius"};
Character[] charList = {'W','D','A','C','I','F','B'};
Integer [][] intTwoDList = {{1, 60, 5},
{20, 40, 5},
{100, 300, 15, 27}};
String [][] stringTwoDList = {{"Quitman", "Valdosta","Atlanta", "Macon"},
{"Gainesville","Tallahassee","Jacksonville"}};
ArrayList aList = new ArrayList<>();
aList.add("Tony");
aList.add("Paige");
aList.add("Denzel");
//Create an object
MyGenerics object = new MyGenerics();
//Display different lists
object.displayOneDList(intList,"Integer One D Array");
object.displayOneDList(doubleList,"Double One D Array");
object.displayOneDList(stringList,"String One D Array");
object.displayOneDList(charList,"Character One D Array");
object.displayTwoDList(intTwoDList,"Integer Two D Array");
object.displayTwoDList(stringTwoDList,"string Two D Array");
object.displayArrayList(aList,"A String arraylist");
//display largest in list
System.out.println ("tLargest value is one-d integer list is: t" + object.max(intList));
System.out.println ("tLargest value is one-d double list is: t" + object.max(doubleList));
System.out.println ("tLargest value is one-d string list is: t" + object.max(stringList));
System.out.println ("tLargest value is one-d character list is: t" + object.max(charList));
System.out.println ("tLargest value is two-d integer list is: t" + object.max(intTwoDList));
System.out.println ("tLargest value is two-d string list is: t" + object.max(stringTwoDList));
System.out.println ("tLargest value is an arrayList is: t" + object.largest(aList));
//Sorting
object.sort(intList);
object.sort(doubleList);
object.sort(stringList);
object.sort(charList);
object.sort(aList);
//Dispaly sorted lists
object.displayOneDList(intList,"Integer One D Array");
object.displayOneDList(doubleList,"Double One D Array");
object.displayOneDList(stringList,"String One D Array");
object.displayOneDList(charList,"Character One D Array");
object.displayArrayList(aList,"A String arraylist");
//BinarySearch
System.out.println ("tThe location of value 20 in intList is: t" +
object.binarySearch(intList,20));
System.out.println ("tThe location of value 77 in intList is: t" +
object.binarySearch(intList,77));
System.out.println ("tThe location of value 'C' in charList is: t" +
object.binarySearch(charList,'C'));
System.out.println ("tThe location of value "Austin" in stringList is: t" +
object.binarySearch(stringList,"Austin"));
}
}
Sample output:
List Name: Integer One D Array
4 7 2 20 30 22
List Name: Double One D Array
4.0 7.5 2.3 20.7 30.1 22.8
List Name: String One D Array
Tony Paige Denzel Travis Austin Thomas Demetrius
List Name: Character One D Array
W D A C I F B
List Name: Integer Two D Array
1 1 60 5
2 20 40 5
3 100 300 15 27
List Name: string Two D Array
1 Quitman Valdosta Atlanta Macon
2 Gainesville Tallahassee Jacksonville
List Name: A String arraylist
Tony Paige Denzel
Largest value is one-d integer list is: 30
Largest value is one-d double list is: 30.1
Largest value is one-d string list is: Travis
Largest value is one-d character list is: W
Largest value is two-d integer list is: 300
Largest value is two-d string list is: Valdosta
Largest value is an arrayList is: Tony
List Name: Integer One D Array
2 4 7 20 22 30
List Name: Double One D Array
2.3 4.0 7.5 20.7 22.8 30.1
List Name: String One D Array
Austin Demetrius Denzel Paige Travis Thomas Tony
List Name: Character One D Array
A B C D F I W
List Name: A String arraylist
Damieona Denzel Paige Tony
The location of value 20 in intList is: 3
The location of value 77 in intList is: -7
The location of value 'C' in charList is: 2
The location of value "Austin" in stringList is: 0
Solution
/** **************************************************************************
* The generic Binary Search Tree class.
*
*****************************************************************************/
import java.util.*;
public class BST > implements Iterable
{
public static void main(String[] args)
{
Integer[] a = {1,5,2,7,4};
BST bst = new BST();
for(Integer n : a) bst.insert(n);
bst.preOrderTraversal();
System.out.println();
//testing comparator
//build a mirror BST with a rule: Left > Parent > Right
//code for the comparator at the bottom of the file
bst = new BST(new MyComp1());
for(Integer n : a) bst.insert(n);
bst.preOrderTraversal();
System.out.println();
bst.inOrderTraversal();
System.out.println();
for(Integer n : bst) System.out.print(n);
System.out.println();
System.out.println(bst);
//testing restoring a tree from two given traversals
bst.restore(new Integer[] {11,8,6,4,7,10,19,43,31,29,37,49},
new Integer[] {4,6,7,8,10,11,19,29,31,37,43,49});
bst.preOrderTraversal();
System.out.println();
bst.inOrderTraversal();
System.out.println();
//testing diameter
System.out.println("diameter = " + bst.diameter());
//testing width
System.out.println("width = " + bst.width());
}
private Node root;
private Comparator comparator;
public BST()
{
root = null;
comparator = null;
}
public BST(Comparator comp)
{
root = null;
comparator = comp;
}
private int compare(T x, T y)
{
if(comparator == null) return x.compareTo(y);
else
return comparator.compare(x,y);
}
/*****************************************************
*
* INSERT
*
******************************************************/
public void insert(T data)
{
root = insert(root, data);
}
private Node insert(Node p, T toInsert)
{
if (p == null)
return new Node(toInsert);
if (compare(toInsert, p.data) == 0)
return p;
if (compare(toInsert, p.data) < 0)
p.left = insert(p.left, toInsert);
else
p.right = insert(p.right, toInsert);
return p;
}
/*****************************************************
*
* SEARCH
*
******************************************************/
public boolean search(T toSearch)
{
return search(root, toSearch);
}
private boolean search(Node p, T toSearch)
{
if (p == null)
return false;
else
if (compare(toSearch, p.data) == 0)
return true;
else
if (compare(toSearch, p.data) < 0)
return search(p.left, toSearch);
else
return search(p.right, toSearch);
}
/*****************************************************
*
* DELETE
*
******************************************************/
public void delete(T toDelete)
{
root = delete(root, toDelete);
}
private Node delete(Node p, T toDelete)
{
if (p == null) throw new RuntimeException("cannot delete.");
else
if (compare(toDelete, p.data) < 0)
p.left = delete (p.left, toDelete);
else
if (compare(toDelete, p.data) > 0)
p.right = delete (p.right, toDelete);
else
{
if (p.left == null) return p.right;
else
if (p.right == null) return p.left;
else
{
// get data from the rightmost node in the left subtree
p.data = retrieveData(p.left);
// delete the rightmost node in the left subtree
p.left = delete(p.left, p.data) ;
}
}
return p;
}
private T retrieveData(Node p)
{
while (p.right != null) p = p.right;
return p.data;
}
/*************************************************
*
* toString
*
**************************************************/
public String toString()
{
StringBuffer sb = new StringBuffer();
for(T data : this) sb.append(data.toString());
return sb.toString();
}
/*************************************************
*
* TRAVERSAL
*
**************************************************/
public void preOrderTraversal()
{
preOrderHelper(root);
}
private void preOrderHelper(Node r)
{
if (r != null)
{
System.out.print(r+" ");
preOrderHelper(r.left);
preOrderHelper(r.right);
}
}
public void inOrderTraversal()
{
inOrderHelper(root);
}
private void inOrderHelper(Node r)
{
if (r != null)
{
inOrderHelper(r.left);
System.out.print(r+" ");
inOrderHelper(r.right);
}
}
/*************************************************
*
* CLONE
*
**************************************************/
public BST clone()
{
BST twin = null;
if(comparator == null)
twin = new BST();
else
twin = new BST(comparator);
twin.root = cloneHelper(root);
return twin;
}
private Node cloneHelper(Node p)
{
if(p == null)
return null;
else
return new Node(p.data, cloneHelper(p.left), cloneHelper(p.right));
}
/*************************************************
*
* MISC
*
**************************************************/
public int height()
{
return height(root);
}
private int height(Node p)
{
if(p == null) return -1;
else
return 1 + Math.max( height(p.left), height(p.right));
}
public int countLeaves()
{
return countLeaves(root);
}
private int countLeaves(Node p)
{
if(p == null) return 0;
else
if(p.left == null && p.right == null) return 1;
else
return countLeaves(p.left) + countLeaves(p.right);
}
//This method restores a BST given preorder and inorder traversals
public void restore(T[] pre, T[] in)
{
root = restore(pre, 0, pre.length-1, in, 0, in.length-1);
}
private Node restore(T[] pre, int preL, int preR, T[] in, int inL, int inR)
{
if(preL <= preR)
{
int count = 0;
//find the root in the inorder array
while(pre[preL] != in[inL + count]) count++;
Node tmp = new Node(pre[preL]);
tmp.left = restore(pre, preL+1, preL + count, in, inL, inL +count-1);
tmp.right = restore(pre, preL+count+1, preR, in, inL+count+1, inR);
return tmp;
}
else
return null;
}
//The width of a binary tree is the maximum number of elements on one level of the tree.
public int width()
{
int max = 0;
for(int k = 0; k <= height(); k++)
{
int tmp = width(root, k);
if(tmp > max) max = tmp;
}
return max;
}
//rerturns the number of node on a given level
public int width(Node p, int depth)
{
if(p==null) return 0;
else
if(depth == 0) return 1;
else
return width(p.left, depth-1) + width(p.right, depth-1);
}
//The diameter of a tree is the number of nodes
//on the longest path between two leaves in the tree.
public int diameter()
{
return diameter(root);
}
private int diameter(Node p)
{
if(p==null) return 0;
//the path goes through the root
int len1 = height(p.left) + height(p.right) +3;
//the path does not pass the root
int len2 = Math.max(diameter(p.left), diameter(p.right));
return Math.max(len1, len2);
}
/*****************************************************
*
* TREE ITERATOR
*
******************************************************/
public Iterator iterator()
{
return new MyIterator();
}
//pre-order
private class MyIterator implements Iterator
{
Stack> stk = new Stack>();
public MyIterator()
{
if(root != null) stk.push(root);
}
public boolean hasNext()
{
return !stk.isEmpty();
}
public T next()
{
Node cur = stk.peek();
if(cur.left != null)
{
stk.push(cur.left);
}
else
{
Node tmp = stk.pop();
while( tmp.right == null )
{
if(stk.isEmpty()) return cur.data;
tmp = stk.pop();
}
stk.push(tmp.right);
}
return cur.data;
}//end of next()
public void remove()
{
}
}//end of MyIterator
/*****************************************************
*
* the Node class
*
******************************************************/
private class Node
{
private T data;
private Node left, right;
public Node(T data, Node l, Node r)
{
left = l; right = r;
this.data = data;
}
public Node(T data)
{
this(data, null, null);
}
public String toString()
{
return data.toString();
}
} //end of Node
}//end of BST
class MyComp1 implements Comparator
{
public int compare(Integer x, Integer y)
{
return y-x;
}
}

More Related Content

Similar to (In java language)1. Use recursion in implementing the binarySearc.pdf

PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfPLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfmallik3000
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfdhavalbl38
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
 
Tested on EclipseBoth class should be in same package.pdf
Tested on EclipseBoth class should be in same package.pdfTested on EclipseBoth class should be in same package.pdf
Tested on EclipseBoth class should be in same package.pdfanupamagarud8
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdfarshiartpalace
 
operating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfoperating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfaquadreammail
 
java-introduction.pdf
java-introduction.pdfjava-introduction.pdf
java-introduction.pdfDngTin307322
 
Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2sotlsoc
 
Treatment, Architecture and Threads
Treatment, Architecture and ThreadsTreatment, Architecture and Threads
Treatment, Architecture and ThreadsMathias Seguy
 
1 The goal is to implement DataStructuresArrayStack accor.pdf
1 The goal is to implement DataStructuresArrayStack accor.pdf1 The goal is to implement DataStructuresArrayStack accor.pdf
1 The goal is to implement DataStructuresArrayStack accor.pdfsaradashata
 
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfC++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfrohit219406
 
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdfarihantmobileselepun
 
HELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdfHELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdffatoryoutlets
 
Complete in JavaCardApp.javapublic class CardApp { private.pdf
Complete in JavaCardApp.javapublic class CardApp {   private.pdfComplete in JavaCardApp.javapublic class CardApp {   private.pdf
Complete in JavaCardApp.javapublic class CardApp { private.pdfMAYANKBANSAL1981
 
for initializer_list include ltinitializer_listgt .pdf
 for initializer_list include ltinitializer_listgt .pdf for initializer_list include ltinitializer_listgt .pdf
for initializer_list include ltinitializer_listgt .pdfajay1317
 

Similar to (In java language)1. Use recursion in implementing the binarySearc.pdf (20)

PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfPLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
 
Quiz using C++
Quiz using C++Quiz using C++
Quiz using C++
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
Tested on EclipseBoth class should be in same package.pdf
Tested on EclipseBoth class should be in same package.pdfTested on EclipseBoth class should be in same package.pdf
Tested on EclipseBoth class should be in same package.pdf
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
operating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfoperating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdf
 
Java
JavaJava
Java
 
java-introduction.pdf
java-introduction.pdfjava-introduction.pdf
java-introduction.pdf
 
Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2
 
Java Print method
Java  Print methodJava  Print method
Java Print method
 
Treatment, Architecture and Threads
Treatment, Architecture and ThreadsTreatment, Architecture and Threads
Treatment, Architecture and Threads
 
1 The goal is to implement DataStructuresArrayStack accor.pdf
1 The goal is to implement DataStructuresArrayStack accor.pdf1 The goal is to implement DataStructuresArrayStack accor.pdf
1 The goal is to implement DataStructuresArrayStack accor.pdf
 
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfC++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
 
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
HELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdfHELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdf
 
Complete in JavaCardApp.javapublic class CardApp { private.pdf
Complete in JavaCardApp.javapublic class CardApp {   private.pdfComplete in JavaCardApp.javapublic class CardApp {   private.pdf
Complete in JavaCardApp.javapublic class CardApp { private.pdf
 
for initializer_list include ltinitializer_listgt .pdf
 for initializer_list include ltinitializer_listgt .pdf for initializer_list include ltinitializer_listgt .pdf
for initializer_list include ltinitializer_listgt .pdf
 

More from rbjain2007

Write a couple of paragraphs describing molecularmicroscopic view of.pdf
Write a couple of paragraphs describing molecularmicroscopic view of.pdfWrite a couple of paragraphs describing molecularmicroscopic view of.pdf
Write a couple of paragraphs describing molecularmicroscopic view of.pdfrbjain2007
 
Write a C program that reads input as a stream of characters until e.pdf
Write a C program that reads input as a stream of characters until e.pdfWrite a C program that reads input as a stream of characters until e.pdf
Write a C program that reads input as a stream of characters until e.pdfrbjain2007
 
Which of the following traits would you expect to find in the transi.pdf
Which of the following traits would you expect to find in the transi.pdfWhich of the following traits would you expect to find in the transi.pdf
Which of the following traits would you expect to find in the transi.pdfrbjain2007
 
Why is RNA consideref to have attributes of both nucleic acids and.pdf
Why is RNA consideref to have attributes of both nucleic acids and.pdfWhy is RNA consideref to have attributes of both nucleic acids and.pdf
Why is RNA consideref to have attributes of both nucleic acids and.pdfrbjain2007
 
Which of these is the strongest bond double covalent bond hydrogen .pdf
Which of these is the strongest bond  double covalent bond  hydrogen .pdfWhich of these is the strongest bond  double covalent bond  hydrogen .pdf
Which of these is the strongest bond double covalent bond hydrogen .pdfrbjain2007
 
When a phosphate group is found in watera) The partially-negative.pdf
When a phosphate group is found in watera) The partially-negative.pdfWhen a phosphate group is found in watera) The partially-negative.pdf
When a phosphate group is found in watera) The partially-negative.pdfrbjain2007
 
what is the basic shape of individual cyanobacterial cells Contrast.pdf
what is the basic shape of individual cyanobacterial cells Contrast.pdfwhat is the basic shape of individual cyanobacterial cells Contrast.pdf
what is the basic shape of individual cyanobacterial cells Contrast.pdfrbjain2007
 
What is an occupancy grid and how can it be used What are some of t.pdf
What is an occupancy grid and how can it be used What are some of t.pdfWhat is an occupancy grid and how can it be used What are some of t.pdf
What is an occupancy grid and how can it be used What are some of t.pdfrbjain2007
 
what are three types of IC sensors that can be used in a digital fan.pdf
what are three types of IC sensors that can be used in a digital fan.pdfwhat are three types of IC sensors that can be used in a digital fan.pdf
what are three types of IC sensors that can be used in a digital fan.pdfrbjain2007
 
What are 3 of the main functions of the HL7 StandardDiscuss the i.pdf
What are 3 of the main functions of the HL7 StandardDiscuss the i.pdfWhat are 3 of the main functions of the HL7 StandardDiscuss the i.pdf
What are 3 of the main functions of the HL7 StandardDiscuss the i.pdfrbjain2007
 
Using your own words, describe the path of sperm from the beginning .pdf
Using your own words, describe the path of sperm from the beginning .pdfUsing your own words, describe the path of sperm from the beginning .pdf
Using your own words, describe the path of sperm from the beginning .pdfrbjain2007
 
The tetany that occurs in death vs tetanus infections occur for diff.pdf
The tetany that occurs in death vs tetanus infections occur for diff.pdfThe tetany that occurs in death vs tetanus infections occur for diff.pdf
The tetany that occurs in death vs tetanus infections occur for diff.pdfrbjain2007
 
The part of the onion you eat (and the part that carries out pho.pdf
The part of the onion you eat (and the part that  carries out pho.pdfThe part of the onion you eat (and the part that  carries out pho.pdf
The part of the onion you eat (and the part that carries out pho.pdfrbjain2007
 
The nonlinear differential equation x”+x=1+x2 arises in the analysis.pdf
The nonlinear differential equation x”+x=1+x2 arises in the analysis.pdfThe nonlinear differential equation x”+x=1+x2 arises in the analysis.pdf
The nonlinear differential equation x”+x=1+x2 arises in the analysis.pdfrbjain2007
 
Prove or disprove If a group G is such that every proper subgroup is.pdf
Prove or disprove If a group G is such that every proper subgroup is.pdfProve or disprove If a group G is such that every proper subgroup is.pdf
Prove or disprove If a group G is such that every proper subgroup is.pdfrbjain2007
 
PART C Assessments Terms Articular cartilage Compact bone Epiphyseal.pdf
PART C Assessments Terms Articular cartilage Compact bone Epiphyseal.pdfPART C Assessments Terms Articular cartilage Compact bone Epiphyseal.pdf
PART C Assessments Terms Articular cartilage Compact bone Epiphyseal.pdfrbjain2007
 
Modern orangutans most likely evolved froma. Dryopithecus.b. Siv.pdf
Modern orangutans most likely evolved froma. Dryopithecus.b. Siv.pdfModern orangutans most likely evolved froma. Dryopithecus.b. Siv.pdf
Modern orangutans most likely evolved froma. Dryopithecus.b. Siv.pdfrbjain2007
 
MasteringBiology Ch. Google Chrome Secure https session masteringbi.pdf
MasteringBiology Ch. Google Chrome Secure https session masteringbi.pdfMasteringBiology Ch. Google Chrome Secure https session masteringbi.pdf
MasteringBiology Ch. Google Chrome Secure https session masteringbi.pdfrbjain2007
 
male fireflies are recognized by females of their species by the pat.pdf
male fireflies are recognized by females of their species by the pat.pdfmale fireflies are recognized by females of their species by the pat.pdf
male fireflies are recognized by females of their species by the pat.pdfrbjain2007
 
Let k be the number of ON-state devices in a group of n devices on a .pdf
Let k be the number of ON-state devices in a group of n devices on a .pdfLet k be the number of ON-state devices in a group of n devices on a .pdf
Let k be the number of ON-state devices in a group of n devices on a .pdfrbjain2007
 

More from rbjain2007 (20)

Write a couple of paragraphs describing molecularmicroscopic view of.pdf
Write a couple of paragraphs describing molecularmicroscopic view of.pdfWrite a couple of paragraphs describing molecularmicroscopic view of.pdf
Write a couple of paragraphs describing molecularmicroscopic view of.pdf
 
Write a C program that reads input as a stream of characters until e.pdf
Write a C program that reads input as a stream of characters until e.pdfWrite a C program that reads input as a stream of characters until e.pdf
Write a C program that reads input as a stream of characters until e.pdf
 
Which of the following traits would you expect to find in the transi.pdf
Which of the following traits would you expect to find in the transi.pdfWhich of the following traits would you expect to find in the transi.pdf
Which of the following traits would you expect to find in the transi.pdf
 
Why is RNA consideref to have attributes of both nucleic acids and.pdf
Why is RNA consideref to have attributes of both nucleic acids and.pdfWhy is RNA consideref to have attributes of both nucleic acids and.pdf
Why is RNA consideref to have attributes of both nucleic acids and.pdf
 
Which of these is the strongest bond double covalent bond hydrogen .pdf
Which of these is the strongest bond  double covalent bond  hydrogen .pdfWhich of these is the strongest bond  double covalent bond  hydrogen .pdf
Which of these is the strongest bond double covalent bond hydrogen .pdf
 
When a phosphate group is found in watera) The partially-negative.pdf
When a phosphate group is found in watera) The partially-negative.pdfWhen a phosphate group is found in watera) The partially-negative.pdf
When a phosphate group is found in watera) The partially-negative.pdf
 
what is the basic shape of individual cyanobacterial cells Contrast.pdf
what is the basic shape of individual cyanobacterial cells Contrast.pdfwhat is the basic shape of individual cyanobacterial cells Contrast.pdf
what is the basic shape of individual cyanobacterial cells Contrast.pdf
 
What is an occupancy grid and how can it be used What are some of t.pdf
What is an occupancy grid and how can it be used What are some of t.pdfWhat is an occupancy grid and how can it be used What are some of t.pdf
What is an occupancy grid and how can it be used What are some of t.pdf
 
what are three types of IC sensors that can be used in a digital fan.pdf
what are three types of IC sensors that can be used in a digital fan.pdfwhat are three types of IC sensors that can be used in a digital fan.pdf
what are three types of IC sensors that can be used in a digital fan.pdf
 
What are 3 of the main functions of the HL7 StandardDiscuss the i.pdf
What are 3 of the main functions of the HL7 StandardDiscuss the i.pdfWhat are 3 of the main functions of the HL7 StandardDiscuss the i.pdf
What are 3 of the main functions of the HL7 StandardDiscuss the i.pdf
 
Using your own words, describe the path of sperm from the beginning .pdf
Using your own words, describe the path of sperm from the beginning .pdfUsing your own words, describe the path of sperm from the beginning .pdf
Using your own words, describe the path of sperm from the beginning .pdf
 
The tetany that occurs in death vs tetanus infections occur for diff.pdf
The tetany that occurs in death vs tetanus infections occur for diff.pdfThe tetany that occurs in death vs tetanus infections occur for diff.pdf
The tetany that occurs in death vs tetanus infections occur for diff.pdf
 
The part of the onion you eat (and the part that carries out pho.pdf
The part of the onion you eat (and the part that  carries out pho.pdfThe part of the onion you eat (and the part that  carries out pho.pdf
The part of the onion you eat (and the part that carries out pho.pdf
 
The nonlinear differential equation x”+x=1+x2 arises in the analysis.pdf
The nonlinear differential equation x”+x=1+x2 arises in the analysis.pdfThe nonlinear differential equation x”+x=1+x2 arises in the analysis.pdf
The nonlinear differential equation x”+x=1+x2 arises in the analysis.pdf
 
Prove or disprove If a group G is such that every proper subgroup is.pdf
Prove or disprove If a group G is such that every proper subgroup is.pdfProve or disprove If a group G is such that every proper subgroup is.pdf
Prove or disprove If a group G is such that every proper subgroup is.pdf
 
PART C Assessments Terms Articular cartilage Compact bone Epiphyseal.pdf
PART C Assessments Terms Articular cartilage Compact bone Epiphyseal.pdfPART C Assessments Terms Articular cartilage Compact bone Epiphyseal.pdf
PART C Assessments Terms Articular cartilage Compact bone Epiphyseal.pdf
 
Modern orangutans most likely evolved froma. Dryopithecus.b. Siv.pdf
Modern orangutans most likely evolved froma. Dryopithecus.b. Siv.pdfModern orangutans most likely evolved froma. Dryopithecus.b. Siv.pdf
Modern orangutans most likely evolved froma. Dryopithecus.b. Siv.pdf
 
MasteringBiology Ch. Google Chrome Secure https session masteringbi.pdf
MasteringBiology Ch. Google Chrome Secure https session masteringbi.pdfMasteringBiology Ch. Google Chrome Secure https session masteringbi.pdf
MasteringBiology Ch. Google Chrome Secure https session masteringbi.pdf
 
male fireflies are recognized by females of their species by the pat.pdf
male fireflies are recognized by females of their species by the pat.pdfmale fireflies are recognized by females of their species by the pat.pdf
male fireflies are recognized by females of their species by the pat.pdf
 
Let k be the number of ON-state devices in a group of n devices on a .pdf
Let k be the number of ON-state devices in a group of n devices on a .pdfLet k be the number of ON-state devices in a group of n devices on a .pdf
Let k be the number of ON-state devices in a group of n devices on a .pdf
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

(In java language)1. Use recursion in implementing the binarySearc.pdf

  • 1. (In java language) 1. Use recursion in implementing the binarySearch method 2. Use Generics in implementing different methods 3. Use the attached driver. Do not modify the driver Please put answers into the skeleton / complete the following given skeleton with the code in java language: import java.util.ArrayList; public class MyGenerics{ //Declarations //**************************************************************************** //No-argument constructor: //**************************************************************************** public MyGenerics (){ }//end of constructor //**************************************************************************** //max: Receives a generic one-dimensional array and returns the maximum // value in the array. //**************************************************************************** public > E max(E[] list){ return null; }//end of max //**************************************************************************** //max: Receives a generic two-dimensional array and returns the maximum // value in the array. //**************************************************************************** public > E max(E[][] list) { return null; } //****************************************************************************
  • 2. //largest: Receives a generic arrayList and returns the maximum // value in the array. //**************************************************************************** public > E largest(ArrayList list) { return null; } //**************************************************************************** //binarySearch: Receives a generic one-dimensional array and a generic key // and returns the location of the key (positive) or // a negative location if not found. //**************************************************************************** public > int binarySearch(E[] list, E key) { int low = 0; int high = list.length - 1; return binarySearch (list, key, low, high); } public > int binarySearch(E[] list, E key, int low, int high) { return -99; // update } //**************************************************************************** //sort: Receives a generic arrayList and returns nothing. //**************************************************************************** public > void sort(ArrayList list) { } //**************************************************************************** //sort: Receives a generic one-dimensional array and returns nothing. //**************************************************************************** public > void sort(E[] list) { } //****************************************************************************
  • 3. //displayOneDList: Receives a generic one-dimensional array and displays its contents //**************************************************************************** public void displayOneDList(E[] list, String listName){ } //**************************************************************************** //displayTwoDList: Receives a generic two-dimensional array & a string name // and displays its contents //**************************************************************************** public void displayTwoDList(E[][] list, String listName){ } //**************************************************************************** //displayArrayList: Receives a generic arraylist & a string name // and displays its contents //**************************************************************************** public void displayArrayList(ArrayList list, String listName){ } } ******************* This is the tester for the given skeleton****************** import java.util.*; public class MyGenerics_Tester{ //Declrations public static void main (String [] args){ //Declarations Integer [] intList = {4, 7, 2, 20, 30, 22}; Double [] doubleList = {4.0, 7.5, 2.3, 20.7, 30.1, 22.8}; String [] stringList = {"Tony","Paige","Denzel","Travis","Austin","Thomas", "Demetrius"}; Character[] charList = {'W','D','A','C','I','F','B'}; Integer [][] intTwoDList = {{1, 60, 5},
  • 4. {20, 40, 5}, {100, 300, 15, 27}}; String [][] stringTwoDList = {{"Quitman", "Valdosta","Atlanta", "Macon"}, {"Gainesville","Tallahassee","Jacksonville"}}; ArrayList aList = new ArrayList<>(); aList.add("Tony"); aList.add("Paige"); aList.add("Denzel"); //Create an object MyGenerics object = new MyGenerics(); //Display different lists object.displayOneDList(intList,"Integer One D Array"); object.displayOneDList(doubleList,"Double One D Array"); object.displayOneDList(stringList,"String One D Array"); object.displayOneDList(charList,"Character One D Array"); object.displayTwoDList(intTwoDList,"Integer Two D Array"); object.displayTwoDList(stringTwoDList,"string Two D Array"); object.displayArrayList(aList,"A String arraylist"); //display largest in list System.out.println ("tLargest value is one-d integer list is: t" + object.max(intList)); System.out.println ("tLargest value is one-d double list is: t" + object.max(doubleList)); System.out.println ("tLargest value is one-d string list is: t" + object.max(stringList)); System.out.println ("tLargest value is one-d character list is: t" + object.max(charList)); System.out.println ("tLargest value is two-d integer list is: t" + object.max(intTwoDList)); System.out.println ("tLargest value is two-d string list is: t" + object.max(stringTwoDList)); System.out.println ("tLargest value is an arrayList is: t" + object.largest(aList)); //Sorting object.sort(intList); object.sort(doubleList); object.sort(stringList); object.sort(charList);
  • 5. object.sort(aList); //Dispaly sorted lists object.displayOneDList(intList,"Integer One D Array"); object.displayOneDList(doubleList,"Double One D Array"); object.displayOneDList(stringList,"String One D Array"); object.displayOneDList(charList,"Character One D Array"); object.displayArrayList(aList,"A String arraylist"); //BinarySearch System.out.println ("tThe location of value 20 in intList is: t" + object.binarySearch(intList,20)); System.out.println ("tThe location of value 77 in intList is: t" + object.binarySearch(intList,77)); System.out.println ("tThe location of value 'C' in charList is: t" + object.binarySearch(charList,'C')); System.out.println ("tThe location of value "Austin" in stringList is: t" + object.binarySearch(stringList,"Austin")); } } Sample output: List Name: Integer One D Array 4 7 2 20 30 22 List Name: Double One D Array 4.0 7.5 2.3 20.7 30.1 22.8 List Name: String One D Array Tony Paige Denzel Travis Austin Thomas Demetrius List Name: Character One D Array W D A C I F B List Name: Integer Two D Array 1 1 60 5 2 20 40 5 3 100 300 15 27 List Name: string Two D Array 1 Quitman Valdosta Atlanta Macon 2 Gainesville Tallahassee Jacksonville
  • 6. List Name: A String arraylist Tony Paige Denzel Largest value is one-d integer list is: 30 Largest value is one-d double list is: 30.1 Largest value is one-d string list is: Travis Largest value is one-d character list is: W Largest value is two-d integer list is: 300 Largest value is two-d string list is: Valdosta Largest value is an arrayList is: Tony List Name: Integer One D Array 2 4 7 20 22 30 List Name: Double One D Array 2.3 4.0 7.5 20.7 22.8 30.1 List Name: String One D Array Austin Demetrius Denzel Paige Travis Thomas Tony List Name: Character One D Array A B C D F I W List Name: A String arraylist Damieona Denzel Paige Tony The location of value 20 in intList is: 3 The location of value 77 in intList is: -7 The location of value 'C' in charList is: 2 The location of value "Austin" in stringList is: 0 Solution /** ************************************************************************** * The generic Binary Search Tree class. * *****************************************************************************/ import java.util.*; public class BST > implements Iterable { public static void main(String[] args) { Integer[] a = {1,5,2,7,4};
  • 7. BST bst = new BST(); for(Integer n : a) bst.insert(n); bst.preOrderTraversal(); System.out.println(); //testing comparator //build a mirror BST with a rule: Left > Parent > Right //code for the comparator at the bottom of the file bst = new BST(new MyComp1()); for(Integer n : a) bst.insert(n); bst.preOrderTraversal(); System.out.println(); bst.inOrderTraversal(); System.out.println(); for(Integer n : bst) System.out.print(n); System.out.println(); System.out.println(bst); //testing restoring a tree from two given traversals bst.restore(new Integer[] {11,8,6,4,7,10,19,43,31,29,37,49}, new Integer[] {4,6,7,8,10,11,19,29,31,37,43,49}); bst.preOrderTraversal(); System.out.println(); bst.inOrderTraversal(); System.out.println(); //testing diameter System.out.println("diameter = " + bst.diameter()); //testing width System.out.println("width = " + bst.width()); } private Node root; private Comparator comparator; public BST() { root = null; comparator = null;
  • 8. } public BST(Comparator comp) { root = null; comparator = comp; } private int compare(T x, T y) { if(comparator == null) return x.compareTo(y); else return comparator.compare(x,y); } /***************************************************** * * INSERT * ******************************************************/ public void insert(T data) { root = insert(root, data); } private Node insert(Node p, T toInsert) { if (p == null) return new Node(toInsert); if (compare(toInsert, p.data) == 0) return p; if (compare(toInsert, p.data) < 0) p.left = insert(p.left, toInsert); else p.right = insert(p.right, toInsert); return p; } /***************************************************** * * SEARCH
  • 9. * ******************************************************/ public boolean search(T toSearch) { return search(root, toSearch); } private boolean search(Node p, T toSearch) { if (p == null) return false; else if (compare(toSearch, p.data) == 0) return true; else if (compare(toSearch, p.data) < 0) return search(p.left, toSearch); else return search(p.right, toSearch); } /***************************************************** * * DELETE * ******************************************************/ public void delete(T toDelete) { root = delete(root, toDelete); } private Node delete(Node p, T toDelete) { if (p == null) throw new RuntimeException("cannot delete."); else if (compare(toDelete, p.data) < 0) p.left = delete (p.left, toDelete); else if (compare(toDelete, p.data) > 0)
  • 10. p.right = delete (p.right, toDelete); else { if (p.left == null) return p.right; else if (p.right == null) return p.left; else { // get data from the rightmost node in the left subtree p.data = retrieveData(p.left); // delete the rightmost node in the left subtree p.left = delete(p.left, p.data) ; } } return p; } private T retrieveData(Node p) { while (p.right != null) p = p.right; return p.data; } /************************************************* * * toString * **************************************************/ public String toString() { StringBuffer sb = new StringBuffer(); for(T data : this) sb.append(data.toString()); return sb.toString(); } /************************************************* * * TRAVERSAL *
  • 11. **************************************************/ public void preOrderTraversal() { preOrderHelper(root); } private void preOrderHelper(Node r) { if (r != null) { System.out.print(r+" "); preOrderHelper(r.left); preOrderHelper(r.right); } } public void inOrderTraversal() { inOrderHelper(root); } private void inOrderHelper(Node r) { if (r != null) { inOrderHelper(r.left); System.out.print(r+" "); inOrderHelper(r.right); } } /************************************************* * * CLONE * **************************************************/ public BST clone() { BST twin = null; if(comparator == null)
  • 12. twin = new BST(); else twin = new BST(comparator); twin.root = cloneHelper(root); return twin; } private Node cloneHelper(Node p) { if(p == null) return null; else return new Node(p.data, cloneHelper(p.left), cloneHelper(p.right)); } /************************************************* * * MISC * **************************************************/ public int height() { return height(root); } private int height(Node p) { if(p == null) return -1; else return 1 + Math.max( height(p.left), height(p.right)); } public int countLeaves() { return countLeaves(root); } private int countLeaves(Node p) { if(p == null) return 0; else
  • 13. if(p.left == null && p.right == null) return 1; else return countLeaves(p.left) + countLeaves(p.right); } //This method restores a BST given preorder and inorder traversals public void restore(T[] pre, T[] in) { root = restore(pre, 0, pre.length-1, in, 0, in.length-1); } private Node restore(T[] pre, int preL, int preR, T[] in, int inL, int inR) { if(preL <= preR) { int count = 0; //find the root in the inorder array while(pre[preL] != in[inL + count]) count++; Node tmp = new Node(pre[preL]); tmp.left = restore(pre, preL+1, preL + count, in, inL, inL +count-1); tmp.right = restore(pre, preL+count+1, preR, in, inL+count+1, inR); return tmp; } else return null; } //The width of a binary tree is the maximum number of elements on one level of the tree. public int width() { int max = 0; for(int k = 0; k <= height(); k++) { int tmp = width(root, k); if(tmp > max) max = tmp; } return max; }
  • 14. //rerturns the number of node on a given level public int width(Node p, int depth) { if(p==null) return 0; else if(depth == 0) return 1; else return width(p.left, depth-1) + width(p.right, depth-1); } //The diameter of a tree is the number of nodes //on the longest path between two leaves in the tree. public int diameter() { return diameter(root); } private int diameter(Node p) { if(p==null) return 0; //the path goes through the root int len1 = height(p.left) + height(p.right) +3; //the path does not pass the root int len2 = Math.max(diameter(p.left), diameter(p.right)); return Math.max(len1, len2); } /***************************************************** * * TREE ITERATOR * ******************************************************/ public Iterator iterator() { return new MyIterator(); } //pre-order private class MyIterator implements Iterator
  • 15. { Stack> stk = new Stack>(); public MyIterator() { if(root != null) stk.push(root); } public boolean hasNext() { return !stk.isEmpty(); } public T next() { Node cur = stk.peek(); if(cur.left != null) { stk.push(cur.left); } else { Node tmp = stk.pop(); while( tmp.right == null ) { if(stk.isEmpty()) return cur.data; tmp = stk.pop(); } stk.push(tmp.right); } return cur.data; }//end of next() public void remove() { } }//end of MyIterator /***************************************************** * * the Node class
  • 16. * ******************************************************/ private class Node { private T data; private Node left, right; public Node(T data, Node l, Node r) { left = l; right = r; this.data = data; } public Node(T data) { this(data, null, null); } public String toString() { return data.toString(); } } //end of Node }//end of BST class MyComp1 implements Comparator { public int compare(Integer x, Integer y) { return y-x; } }