This document contains questions and prompts related to data structures and algorithms topics like arrays, sorting, searching, hash tables, trees, and tree traversals. It asks the reader to analyze, draw, summarize, implement, or describe various concepts through examples, diagrams, pseudocode, or clear written explanations.
linked list
singly linked list
insertion in singly linked list
DELETION IN SINGLY LINKED LIST
Searching a singly linked list
Doubly Linked List
insertion from Doubly linked list
DELETION from Doubly LINKED LIST
Searching a doubly linked list
Circular linked list
2D array in C++ language ,define the concept of c++ Two-Dimensional array .with example .and also Accessing Array Components concept.and Processing Two-Dimensional Arrays.
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output?
Location i = new Location(0, 3);
Location j = new Location(0, 3);
b.add(i);
b.add(j);
System.out.println(b.countOccurrences(i));
A. 0
B. 1
C. 2
D. 3
Suppose that b and c are Integer objects. A typical use of the clone method looks like this:
b = (Integer) c.clone( );
Write a short clear explanation of why the (Integer) type cast is required in this typical example.
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that obj is an Object variable and s is a String variable. Which of the following statements
is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference?
A. A NullPointerException occurs
B. It always returns true.
C. It always returns false.
D. It returns true if y is also a null reference; otherwise it returns false.
Consider the implementation of the Stack using a partially-filled array.
What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array?
A. Both peek and pop would require linear time.
B. Both push and pop would require linear time.
C. The Stack could not be used to check balanced parentheses.
D. The Stack could not be used to evaluate postfix expressions.
Write some lines of code that declares an Integer object, using the Integer wrapper class.
Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
A. 1
B. 2
C. 3
D. 4
E. 5 or more
Consider the usual algorithm to convert an infix expression to a postfix expression.
Suppose that you have read 10 input characters during a conversion and that the
stack now contains the symbols as shown below. Suppose that you read and process
the 11th symbol of the input. What symbol is at the top of the stack in the case where
the 11th symbol is each of the choices shown?
Which of the following stack operations could result in stack underflow?
Answer
A. is_empty
B. pop
C. push
D. Two or more of the above answers
What is the value of the postfix expression 6 3 2 4 + - *:
Answer
A. Something between -15 and -100
B. Something between -5 and -15
C. Something between 5 and -5
D. Something between 5 and 15
E. Something between 15 and 100
1. An array o.
linked list
singly linked list
insertion in singly linked list
DELETION IN SINGLY LINKED LIST
Searching a singly linked list
Doubly Linked List
insertion from Doubly linked list
DELETION from Doubly LINKED LIST
Searching a doubly linked list
Circular linked list
2D array in C++ language ,define the concept of c++ Two-Dimensional array .with example .and also Accessing Array Components concept.and Processing Two-Dimensional Arrays.
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output?
Location i = new Location(0, 3);
Location j = new Location(0, 3);
b.add(i);
b.add(j);
System.out.println(b.countOccurrences(i));
A. 0
B. 1
C. 2
D. 3
Suppose that b and c are Integer objects. A typical use of the clone method looks like this:
b = (Integer) c.clone( );
Write a short clear explanation of why the (Integer) type cast is required in this typical example.
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that obj is an Object variable and s is a String variable. Which of the following statements
is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference?
A. A NullPointerException occurs
B. It always returns true.
C. It always returns false.
D. It returns true if y is also a null reference; otherwise it returns false.
Consider the implementation of the Stack using a partially-filled array.
What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array?
A. Both peek and pop would require linear time.
B. Both push and pop would require linear time.
C. The Stack could not be used to check balanced parentheses.
D. The Stack could not be used to evaluate postfix expressions.
Write some lines of code that declares an Integer object, using the Integer wrapper class.
Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
A. 1
B. 2
C. 3
D. 4
E. 5 or more
Consider the usual algorithm to convert an infix expression to a postfix expression.
Suppose that you have read 10 input characters during a conversion and that the
stack now contains the symbols as shown below. Suppose that you read and process
the 11th symbol of the input. What symbol is at the top of the stack in the case where
the 11th symbol is each of the choices shown?
Which of the following stack operations could result in stack underflow?
Answer
A. is_empty
B. pop
C. push
D. Two or more of the above answers
What is the value of the postfix expression 6 3 2 4 + - *:
Answer
A. Something between -15 and -100
B. Something between -5 and -15
C. Something between 5 and -5
D. Something between 5 and 15
E. Something between 15 and 100
1. An array o.
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
Getting Started
Create a class called Lab8. Use the same setup for setting up your class and main method as you
did for the previous assignments. Be sure to name your file Lab8.java. Additionally, make
another file called Arrays.java. This file will be an object, so simply start it off by declaring an
Arrays class. You can copy the following skeleton and fill in the appropriate code below each of
the comments:
public class Arrays {
/ Instance Variables
// Constructors
// findMin 1
// findMax
// calcSum
// calcAverage
// toString
}
Task Overview
Your task for this lab is to create a class called Arrays with some array processing methods. This
class will maintain an array and the number of elements present in it. Additionally, methods will
be available to display the current min and max elements along with the average of all of them.
Finally, a toString() method will be available to cleanly display all the array elements. Finally,
you will write a simple driver class to test out the above Arrays class.
Part 1: Instance Variables for Arrays
The first thing to do for the Arrays class is to set up its instance variables. Declare the following
(private) instance variables:
• An int array called array ? this will be the array we will be writing methods for.
• An int called count - this represents the number of valid elements in the array.
Part 2:
Constructors for Arrays The Arrays class will have two constructors. The first constructor takes
the maximum size of the array as input as a parameter and initializes the array instance variable
appropriately. It also sets count to size. Finally, it will initialize all of the array elements to some
values between 0 and 10, inclusive. To create this constructor, follow these steps:
• Import java.util.Random to make use of the random number generator.
• Create a constructor with the following header: public Arrays(int size)
• Initialize your array variable and set its size to size (see the chart on page 252 for reference on
initializing arrays). Be very careful that you are setting the value of your array instance variable,
as opposed to creating a new variable called array.
• Set the value of the count variable to size because we will be populating the entire array.
• Copy the following code to the constructor in order to generate random values between 0 and
10, inclusive:
Random rand = new Random();
for (int i = 0; i < count; i++)
{
array[i] = (rand.nextInt(10));
}
Next, create another constructor with the following header: public Arrays(int[] arr). This
constructor will initialize the class by using the passed arr argument in order to fill its instance
variables. The following things need to be done inside of this constructor:
• Set the array variable equal to arr.
• Set the count variable equal to the length of the array.
Part 3: Displaying the Output findMin()
The first method of this class will search the array for the minimum element. Copy the following
code for the findMin method. Note how the count i.
I am Frank P. I am a C++ Programming Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from Malacca, Malaysia. I have been helping students with their homework for the past 9 years. I solve homework related to C++ Programming .
Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Programming Homework.
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
Required to augment the author's Binary Search Tree (BST) code to support these new operations. Method names below are merely suggestions. (The author’s class is attached separately in the file called “authordoc”. I just built a simple test tree in the author’s main method which can be used to test the various operations. )
1. AnyType nthElement(int n) -- returns the n-th element (starting from 1) of the in-order traversal of the BST.
2. int rank( AnyType x ) -- returns the "rank" of x. The rank of an element is its position (starting with 1) in an in-order traversal.
3. AnyType median( ) -- returns the median (middle) element in the BST. If the BST contains an even number of elements, returns the smaller of the two medians.
4. boolean isPerfect( ) -- returns true if the BST is a perfect binary tree.
5. boolean isComplete( ) -- returns true if the BST is a complete binary tree.
6. String toString( int nrLevels ) -- generates the level-order output described in the sample output below.
Most of these operations could easily be implemented by performing an in-order traversal inside the BST and perhaps placing the results in an ArrayList. However, such a method is extremely inefficient. Instead, we are going to achieve faster performance by "augmenting" the BST nodes. You will add a new private integer data member ("tree size") to the BinaryNode which stores the size of the tree rooted at that node (including the root). You must develop your own algorithms for these operations, but obviously you will use the new tree size data member to guide your search. Think before you code and think recursively!
These items cover those topics not addressed elsewhere in the project description. (R) indicates a requirement, (H) indicates a hint, and (N) indicates a note.
1. (R) Although we are only using the BST for integers, the BST must remain a generic class.
2. (R) Duplicate values are not allowed. Attempts to insert a duplicate value should be ignored.
3. (R) Attempts to remove non-existent values should be ignored.
4. (R) From a coding perspective, the easiest way to avoid duplicate insertions or attempting to remove non-existent elements is to first call find( ). However, this technique is NOT permitted for two reasons.
Calling find( ) before each insert/remove doubles the running time for these operations and is therefore inefficient.
Recusively coding the insert/remove methods to handle these situations is a great learning experience.
5. (R) The level order print (PRINT command) outputs the value of each node, the size of the tree rooted at that node, and the value of the node's parent in that order, inside parenthesis, separated by commas. (node value, tree size, parent value). Since the root has no parent, print NULL for the root's parent value. For readability, separate the levels with a blank line and print no more than 6 node/size/parent values per line. If a level requires multiple lines, use consecutive lines (without a blank line between the ...
An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may.
java I am trying to run my code but it is not letting me .pdfadinathassociates
java
I am trying to run my code but it is not letting me i dont know what i should do or fix. Thank you so
much for your help. This is the problem and my code will be on the bottom.
Problem #1 and Only
Dynamic Array of Integers Class
Create a class named DynamicArray that will have convenient functionality similar to JavaScripts
Array object and Javas ArrayList class. The class allows to store array of integers that can grow
and shrink as needed, search for values, remove elements, etc.
You are not allowed to use ArrayList object as well as any methods from java.util.Arrays
class.
Please see the list of required features and methods below.
private int array[] You MUST store the data internally in a regular partially-filled array of integers.
Please DO NOT USE ArrayList. The size of the allocated array is its capacity and will be
discussed below.
private int size. This variable stores the number of occupied elements in the array. Set to 0 in the
constructor.
Constructor with parameter. The parameter defines the capacity (length) of initial array. Allocates
array of given capacity (length), sets size field to 0. In case the parameter given to constructor is 0
or negative, IllegalArgumentException is being thrown.
No-argument constructor. Allocates array of length 3, assigns it to the array field, sets size field to
0.
Copy constructor. The constructor takes an object of type DynamicArray as a parameter and
copies it into the object it creates. The constructor throws IllegalArgumentException if the object
that was passed to copy from is null.
int getSize() returns the number of occupied elements in the array.
int getCapacity() returns the actual size (length) of the partially-filled array
int [] getArray() accessor returns the entire partially-filled array. Make sure you DO NOT return the
private array field, make a copy of it.
int [] toArray() accessor returns an occupied part of the partially-filled array. Make sure you DO
NOT return the private array field. Instead, allocate memory for the new array, copy the occupied
portion of the field into that new object, and return the new array.
public void push(int num) adds a new element to the end of the array and increments the size
field. If the array is full, you need to increase the capacity of the array:
Create a new array with the size equal to double the capacity of the original one.
Copy all the elements from the array field to the new array.
Add the new element to the end of the new array.
Use new array as an array field.
Make sure your method works well when new elements are added to an empty DynamicArray.
public int pop() throws RuntimeException removes the last element of the array and returns it.
Decrements the size field. If the array is empty a RuntimeException with the message Array is
empty must be thrown. At this point check the capacity of the array. If the capacity is 4 times larger
than the number of occupied elements (size), it is time to shrink the array:
Create a new array wi.
Sorted number list implementation with linked listsStep 1 Inspec.pdfalmaniaeyewear
Sorted number list implementation with linked lists
Step 1: Inspect the Node.java file
Inspect the class declaration for a doubly-linked list node in Node.java. Access Node.java by
clicking on the orange arrow next to LabProgram.java at the top of the coding window. The
Node class has three fields:
a double data value,
a reference to the next node, and
a reference to the previous node.
Each field is protected. So code outside of the class must use the provided getter and setter
methods to get or set a field.
Node.java is read only, since no changes are required.
Step 2: Implement the insert() method
A class for a sorted, doubly-linked list is declared in SortedNumberList.java. Implement the
SortedNumberList class's insert() method. The method must create a new node with the
parameter value, then insert the node into the proper sorted position in the linked list. Ex:
Suppose a SortedNumberList's current list is 23 47.25 86, then insert(33.5) is called. A new
node with data value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's
sorted order and yielding: 23 35.5 47.25 86
Step 3: Test in develop mode
Code in main() takes a space-separated list of numbers and inserts each into a SortedNumberList.
The list is displayed after each insertion. Ex: If input is
then output is:
Try various program inputs, ensuring that each outputs a sorted list.
Step 4: Implement the remove() method
Implement the SortedNumberList class's remove() method. The method takes a parameter for the
number to be removed from the list. If the number does not exist in the list, the list is not
changed and false is returned. Otherwise, the first instance of the number is removed from the
list and true is returned.
Uncomment the commented-out part in main() that reads a second input line and removes
numbers from the list. Test in develop mode to ensure that insertion and removal both work
properly, then submit code for grading. Ex: If input is
then output is:
Given templates:
LabProgram.java
import java.util.Scanner;
import java.io.PrintWriter;
public class LabProgram {
// Prints the SortedNumberList's contents, in order from head to tail
public static void printList(SortedNumberList list) {
Node node = list.head;
while (null != node) {
System.out.print(node.getData() + " ");
node = node.getNext();
}
System.out.println();
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String inputLine;
// Read the line of input numbers
inputLine = scnr.nextLine();
// Split on space character
String[] terms = inputLine.split(" ");
// Insert each value and show the sorted list's contents after each insertion
SortedNumberList list = new SortedNumberList();
for (Object term : terms) {
double number = Double.parseDouble(term.toString());
System.out.println("List after inserting " + number + ": ");
list.insert(number);
printList(list);
}
/*
// Read the input line with numbers to remove
inputLine = scnr.nextLine();
terms = inputLine.split(" ".
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
Homework Assignment – Array Technical Document
Write a technical document that describes the structure and use of arrays. The document should
be 3 to 5 pages and include an Introduction section, giving a brief synopsis of the document and
arrays, a Body section, describing arrays and giving an annotated example of their use as a
programming construct, and a conclusion to revisit important information about arrays described
in the Body of the document. Some suggested material to include:
Declaring arrays of various types
Array pointers
Printing and processing arrays
Sorting and searching arrays
Multidimensional arrays
Indexing arrays of various dimension
Array representation in memory by data type
Passing arrays as arguments
If you find any useful images on the Internet, you can use them as long as you cite the source in
end notes.
Solution
Array is a collection of variables of the same type that are referenced by a common name.
Specific elements or variables in the array are accessed by means of index into the array.
If taking about C, In C all arrays consist of contiguous memory locations. The lowest address
corresponds to the first element in the array while the largest address corresponds to the last
element in the array.
C supports both single and multi-dimensional arrays.
1) Single Dimension Arrays:-
Syntax:- type var_name[size];
where type is the type of each element in the array, var_name is any valid identifier, and size is
the number of elements in the array which has to be a constant value.
*Array always use zero as index to first element.
The valid indices for array above are 0 .. 4, i.e. 0 .. number of elements - 1
For Example :- To load an array with values 0 .. 99
int x[100] ;
int i ;
for ( i = 0; i < 100; i++ )
x[i] = i ;
To determine to size of an array at run time the sizeof operator is used. This returns the size in
bytes of its argument. The name of the array is given as the operand
size_of_array = sizeof ( array_name ) ;
2) Initialisg array:-
Arrays can be initialised at time of declaration in the following manner.
type array[ size ] = { value list };
For Example :-
int i[5] = {1, 2, 3, 4, 5 } ;
i[0] = 1, i[1] = 2, etc.
The size specification in the declaration may be omitted which causes the compiler to count the
number of elements in the value list and allocate appropriate storage.
For Example :- int i[ ] = { 1, 2, 3, 4, 5 } ;
3) Multidimensional array:-
Multidimensional arrays of any dimension are possible in C but in practice only two or three
dimensional arrays are workable. The most common multidimensional array is a two
dimensional array for example the computer display, board games, a mathematical matrix etc.
Syntax :type name [ rows ] [ columns ] ;
For Example :- 2D array of dimension 2 X 3.
int d[ 2 ] [ 3 ] ;
A two dimensional array is actually an array of arrays, in the above case an array of two integer
arrays (the rows) each with three elements, and is stored row-wise in memory.
For Example :- Program to fill .
Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of array.
Google interviewer asked for an algorithm to extract the k smallest elements from a set of ordered arrays. I suggested a vectorised bucket sort and merge sort approach. I took the problem offline and produced this analysis and C++.
I am Gabriel C. I am a C Exam Expert at programmingexamhelp.com. I hold a PhD. in Business analyst of Information Technology, Montreal College of Information Technology, Canada. I have been helping students with their exams for the past 8 years. You can hire me to take your exam in C.
Visit programmingexamhelp.com or email support@programmingexamhelp.com. You can also call on +1 678 648 4277 for any assistance with the C Exam.
1. 1. Here is an array with exactly 15 elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Suppose that we are doing a serial search for an element. Circle any elements that will be found by
examining two or fewer numbers from the array.
2. Here is an array with exactly 15 elements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Suppose that we are doing a binary search for an element. Circle any elements that will be found by
examining two or fewer numbers from the array.
3. Implement the body of the following function using a binary search of the array. You do not need
to check the precondition.
public static boolean has42(int[ ] data, int start, int end)
// Precondition: The elements data[start]...data[end] are sorted from smallest
// to largest. This array segment might be empty (indicated by end being less
// than start).
// Postcondition: A true return value indicates that the number 42 appears in
// data[start]...data[end]. A false return value indicates that 42 doesn’t
// appear.
4. Draw a hash table with open addressing and a size of 9. Use the hash function "k%9". Insert the
keys: 5, 29, 20, 0, 27 and 18 into your table (in that order).
5. Suppose you are building an open address hash table with double hashing. The hash table
capacity is n, so that the valid hash table indexes range from 0 to n. Fill in the blanks:
In order to ensure that every array position is examined, the value returned by the second
hash function must be ________________________ with respect to n.
One way to ensure this good behavior is to make n be _______________, and have the
return value of the second hash function range from _________ to _________ (including the
end points).
6. You are writing code for the remove method of a chained hash table. Fill in the blanks in this
pseudocode with the two missing statements. You may use pseudocode yourself, or write actual
Java code:
public void Table remove(Object key)
{
2. ChainedHashNode cursor;
int i;
1. i = key.hashCode( );
2. Make cursor refer to the node that contains an item with the given key
(or set it to null if there is no such node).
3. if (cursor != null)
{
3a. _____________________________________________________________
3b. _____________________________________________________________
}
7. Draw a hash table with chaining and a size of 9. Use the hash function "k%9" to insert the keys 5,
29, 20, 0, and 18 into your table.
8. Suppose that I have the following private instance variables for an open-address hash table:
public class Table
{
privateintmanyItems;
9.private Object[ ] keys;
private Object[ ] data;
privateboolean[ ] hasBeenUsed;
...
The hash table uses open addressing with linear probing. A location [i] of the table that has NEVER
been used will have hasBeenUsed[i] set to false. Other locations have hasBeenUsed[i] set to true.
Complete the implementation of the following method of the Table class. There is no need to check
the precondition, but your code must be as efficient as possible.
publicbooleancontainsKey(Object key)
3. // Postcondition: If key occurs as a key of a record in the table, then
// the method returns true; otherwise the method returns false.
10. Suppose that an open-address hash table has a capacity of 811 and it contains 81 elements.
What is the table's load factor? (An appoximation is fine.)
11. I plan to put 1000 items in a hash table, and I want the average number of accesses in a
successful search to be about 2.0.
A. About how big should the array be if I use open addressing with linear probing? NOTE: For a load
factor of A, the average number of accesses is generally ½(1+1/(1-A)).
12. Here is an array of ten integers:
5 3 8 9 1 7 0 2 6 4
Draw this array after the FIRST iteration of the large loop in a selection sort (sorting from smallest to
largest).
13. Here is an array of ten integers:
5 3 8 9 1 7 0 2 6 4
Draw this array after the FIRST iteration of the large loop in an insertion sort (sorting from smallest
to largest). This iteration has shifted at least one item in the array!
14. Suppose that you are writing a program that has this selectionsort static method available:
voidselectionsort(int[ ] data, int first, int n);
Your program also has an integer array called x, with 10 elements. Write two method activations:
The first activation uses selectionsort to sort all of x; the second call uses selectionsort to sort
x[3]..x[9].
15. Describe a case where quicksort will result in quadratic behavior.
16. Here is an array which has just been partitioned by the first step of quicksort:
3, 0, 2, 4, 5, 8, 7, 6, 9
Which of these elements could be the pivot? (There may be more than one possibility!)
17. Give a concise accurate description of a good way for quicksort to choose a pivot element. Your
approach should be better than "use the entry at location [0]".
18. Give a concise accurate description of a good way for quicksort to improve its performance by
using insertionsort.
19. Here is an array of ten integers:
5 3 8 9 1 7 0 2 6 4
4. Suppose we partition this array using quicksort's partition function and using 5 for the pivot. Draw
the resulting array after the partition finishes.
20. Here is an array of ten integers:
5 3 8 9 1 7 0 2 6 4
Draw this array after the TWO recursive calls of merge sort are completed, and before the final
merge step has occured.
21. Implement the following static method:
private static void merge(int[ ] data, int first, int n1, int n2);
// Precondition: data has at least n1+n2 components starting at
// data[first]. The first n1 elements (from data[first] to
// data[first+n1-1]) are sorted from smallest to largest, and the last
// n2 elements (from data[first+n1] to data[first+n1+n2-1]) are also
// sorted from smallest to largest.
// Postcondition: Starting at data[first, n1+n2 elements of data have been
// rearranged to be sorted from smallest to largest.
22. Write two or three clear sentences to describe how a heapsort works.
23. Fill in the following table for the times to sort an array of n items. Use only big-O notation, and
do not have any extraneous constants in your expressions.
Worst Case Average Case
Binary search of a sorted array
Insertion sort
Merge sort
Quick sort without "median of three" pivot
selection
Quick sort with "median of three" pivot
selection
Selection sort
Heap sort
5. 24. Here is a small binary tree:
14
/
2 11
/ /
1 3 10 30
/ /
7 40
Circle all the leaves. Put a square box around the root. Draw a star around each ancestor of
the node that contains 10. Put a big X through every descendant of the node the contains 10.
25. Draw a full binary tree with at least 6 nodes.
26. Draw a complete binary tree with exactly six nodes. Put a different value in each node.
Then draw an array with six components and show where each of the six node values would
be placed in the array (using the usual array representation of a complete binary tree).
27. Write the instance variables for a new class that could be used for a node in a tree where:
(1) Each node contains int data, (2) Each node has up to four children, and (3) Each node also
has a reference to its parent. Store the references to the children in an array of four
components.
28. Draw a binary taxonomy tree that can be used for these four animals: Rabbit, Horse,
Whale, Snake.
29. Using the BTNode class from, write a new static method of the BTNode class to meet the
following specification. No recursion is needed.
public static void subswap(BTNode root)
// Precondition: Root is the root reference of a binary tree.
// Postcondition: If root is non-null, then the original left subtree below
// this root has been moved and is now the right subtree, and the original
// right subtree is now the left subtree.
// Example original tree: Example new tree:
// 1 1
// / /
// 2 3 3 2
// / /
// 4 5 4 5
30. Redo the previous problem as a new non-static BTNode method.
31. Using the BTNode class from, write a new static method of the BTNode class to meet the
following specification.
public static intmanyNodes(BTNode root)
// Precondition: root_ptr is the root reference of a binary tree.
// Postcondition: The return value is the number of nodes in the tree.
// NOTES: The empty tree has 0 nodes, and a tree with just a root has
// 1 node.
32. Using the BTNode class, write a new static method of the BTNode class to meet the
following specification.
public static inttreeDepth(BTNode root)
// Precondition: root_ptr is the root reference of a binary tree.
// Postcondition: The return value is the depth of the binary tree.
// NOTES: The empty tree has a depth of -1 and a tree with just a root
// has a depth of 0.
33. Suppose IntBTNode is a BTNode with integer data. Write a new static method of the
IntBTNode class to meet the following specification.
34. Suppose IntBTNode is a BTNode with integer data. Write a new static method of the
IntBTNode class to meet the following specification.
public static int count42(IntBTNode root)
// Precondition: root is the root reference of a binary tree (but
6. // NOT NECESSARILY a search tree).
// Postcondition: The return value indicates how many times 42 appears
// in the tree. NOTE: If the tree is empty, the method returns zero.
35. Suppose IntBTNode is a BTNode with integer data. Write a new static method of the
IntBTNode class to meet the following specification.
public static boolean has42(IntBTNode root)
// Precondition: root is the root reference of a binary tree (but
// NOT NECESSARILY a search tree).
// Postcondition: The return value indicates whether 42 appears somewhere
// in the tree. NOTE: If the tree is empty, the method returns false.
36. Suppose IntBTNode is a BTNode with integer data. Write a new static method of the
IntBTNode class to meet the following specification.
public static boolean all42(IntBTNode root)
// Precondition: root is the root reference of a binary tree (but
// NOT NECESSARILY a search tree).
// Postcondition: The return value is true if every node in the tree
// contains 42. NOTE: If the tree is empty, the method returns true.
37. Suppose IntBTNode is a BTNode with integer data. Write a new static method of the
IntBTNode class to meet the following specification.
public static int sum(IntBTNode root)
// Precondition: root is the root reference of a binary tree.
// Postcondition: The return value is the sum of all the data in all the
nodes.
// NOTES: The return value for the empty tree is zero.
38. Suppose that we want to create a binary search tree where each node contains information
of some data type. What additional factor is required for the data type?
39. Suppose that a binary search tree contains the number 42 at a node with two children.
Write two or three clear sentences to describe the process required to delete the 42 from the
tree.
40. Suppose IntBTNode is a BTNodewith integer data. Write a new static method of the
IntBTNode class to meet the following specification. Make the method as efficient as
possible (do not visit nodes unnecessarily).
public static int count42(BTNode root)
// Precondition: root is the root reference of a binary SEARCH tree.
// Postcondition: The return value indicates how many times 42 appears
// in the tree.
41. Suppose IntBTNode is a BTNode with integer data. Write a new static method of the
IntBTNode class to meet the following specification. Make the method as efficient as
possible (do not visit nodes unnecessarily).
public static int max(BTNode root)
// Precondition: root is the root reference of a nonempty binary SEARCH
// tree.
// Postcondition: The return value is the largest value in the tree.
42. Suppose IntBTNode is a BTNode with integer data. Write a new static method of the
IntBTNode class to meet the following specification. Make the method as efficient as
possible (do not visit nodes unnecessarily).
void insert42(BTNode root)
// Precondition: root is the root reference of a binary SEARCH tree.
// Postcondition: One copy of the number 42 has been added to the binary
// search tree.
43. What is the importance of the stopping case in recursive methods?
7. 44. Write a recursive method that has one parameter which is an int value called x. The method
prints x asterisks, followed by x exclamation points. Do NOT use any loops. Do NOT use any variables
other than x.
45. For the tree shown below, determine
a. Which node is the root
b. Which nodes are leaves
c. The tree’s depth
d. The result of preorder, postorder, inorder, and level-order traversals
46.For each node shown on the tree below:
a. Name the parent node
b. List the children
c. List the siblings
d. Compute the height
e. Compute the depth
f. Compute the size
47.What is the output of the following method for the
tree shown below?
1 public static <AnyType> void mysteryPrint(BinaryNode<AnyType> t )
2 {
3 if( t != null )
4 {
5 System.out.println(t.getElement( ) );
6 mysteryPrint(t.getLeft( ) );
7 System.out.println(t.getElement( ) );
8 mysteryPrint(t.getRight( ) );
9 System.out.println(t.getElement( ) );
10 }
11 }
48.Show the stack operations when an inorder and preorder traversal is
applied to the tree.