Recursion

User Generated

Xbbygbal843

Programming

Data Structures for Problem Solving (IT265 -1704A -01)

ctu online

Description

    • Section 5: Recursion
  • Conclusion
  • References
  • New Content
    • Create a pseudo code routine that will ask the user for a number, and then using recursion, generate the factorial of that number.
    • Create fully documented pseudo code to prompt for a number and generate the factorial, including error and bound checking.
    • Create a test plan to show how the program runs and can be executed.

Unformatted Attachment Preview

Running head: THE DATA STRUCTURE USING JAVA Data Structures for Problem Solving(IT265-1802B-01) Antonio Larkin The Data Structure Using Java Instructor: Donald Wilcoxen 6/09/18 1 THE DATA STRUCTURE USING JAVA 2 Abstract The identification of the different data structures is crucial within the java programming script. The understanding of the use of queues and stacks, heaps and trees, the sorting of algorithms increases the speed and efficiency of the usage of data. The proper and efficient planning of the queues, stacks and heaps allow businesses to be more alert in their data and in the hyper competitive market place. THE DATA STRUCTURE USING JAVA 3 Table of Contents Abstract ……………………………………………………………………………………2pg Section 1: lists, stacks and Queues ……………………………………………………….4pg The Stacks ………………………………………………………………………………….4-10pg The Queues………………………………………………………………………………10-16pg Section 2: Heaps and Trees ……………………………………………………………17-25pg Section 3: sorting the Algorithms ……………………………………………………….26-37pg Section 4: searching ……………………………………………………………………38-48pg Section 5: recursion: …………………………………………………………………….....49pg Reference …………………………………………………………………………………...50pg THE DATA STRUCTURE USING JAVA Section 1: lists, stacks and Queues The Stacks: import java.io.*; class Node { public String element; public Node next; public Node(String value) { element = value; } public void displayNode() { System.out.println("Element [" + element + "] "); } 4 THE DATA STRUCTURE USING JAVA } class LinkedList { private Node first; public LinkedList() { first = null; } public boolean isEmpty() { return (first==null); } public void push(String value) //inserts at beginning of list { Node newNode = new Node(value); newNode.next = first; 5 THE DATA STRUCTURE USING JAVA first = newNode; } public Node pop() //deletes at beginning of list { Node temp = first; first = first.next; return temp; } public void display() { System.out.println("Elements:"); Node current = first; while(current != null) { current.displayNode(); current = current.next; 6 THE DATA STRUCTURE USING JAVA } System.out.println(""); } } class Stack { private LinkedList stackLinkedList; public Stack() { stackLinkedList = new LinkedList(); } public void push(String value) { stackLinkedList.push(value); } public Node pop() { 7 THE DATA STRUCTURE USING JAVA return stackLinkedList.pop(); } public boolean isEmpty() { return stackLinkedList.isEmpty(); } public void displayStack() { System.out.println("Stack:"); stackLinkedList.display(); } } class StackCall { public static void main(String[] args) throws IOException { Stack sample = new Stack(); 8 THE DATA STRUCTURE USING JAVA System.out.println("Adding two elements into the stack"); sample.push("one"); sample.push("two"); sample.displayStack(); System.out.println("Adding two more elements into the stack"); sample.push("three"); sample.push("four"); sample.displayStack(); System.out.println("Removing two elements from the stack"); sample.pop(); } } sample.pop(); 9 THE DATA STRUCTURE USING JAVA sample.displayStack(); The Queues: import java.io.*; class Node { public String element; public Node next; public Node(String val) { element = val; } public void displayNode() 10 THE DATA STRUCTURE USING JAVA { System.out.println("Element [" + element + "]"); } } class LinkedList { private Node start; private Node end; public LinkedList() { start = null; end = null; } public boolean isEmpty() { return start==null; } 11 THE DATA STRUCTURE USING JAVA public void enqueue(String val) //Insert node at the end of list { Node newNode = new Node(val); if( isEmpty() ) start = newNode; else end.next = newNode; end = newNode; } public String dequeue() //delete the node from the beginning of the list { String temp = start.element; if(start.next == null) end = null; start = start.next; 12 THE DATA STRUCTURE USING JAVA return temp; } public void displayList() { System.out.println("Elements:"); Node current = start; while(current != null) { current.displayNode(); current = current.next; } System.out.println(""); } } class Queue { private LinkedList queueLinkedList; 13 THE DATA STRUCTURE USING JAVA public Queue() { queueLinkedList = new LinkedList(); } public boolean isEmpty() { return queueLinkedList.isEmpty(); } public void enqueue(String element) { queueLinkedList.enqueue(element); } public String dequeue() { return queueLinkedList.dequeue(); } public void displayQueue() 14 THE DATA STRUCTURE USING JAVA { System.out.println("Queue:"); queueLinkedList.displayList(); } } class QueueCall { public static void main(String[] args) { Queue sample = new Queue(); System.out.println("Adding two elements into the queue"); sample.enqueue("one"); sample.enqueue("two"); sample.displayQueue(); } 15 THE DATA STRUCTURE USING JAVA } System.out.println("Adding two more elements into the queue"); sample.enqueue("three"); sample.enqueue("four"); sample.displayQueue(); System.out.println("Removing two elements from the queue"); sample.dequeue(); sample.dequeue(); sample.displayQueue(); 16 THE DATA STRUCTURE USING JAVA 17 Section 2: Heaps and Trees Implementation of the pseudo code for the hash table Determining and solving the collisions with the linked list Solution to Heaps, Trees, and Hashing Section 2: The implementation of the pseudo code for the hash table (for operation Insert) is shown below: public class Insert { public Insert( ) { this( size ); } public Insert( int size ) { theLists = new L[ nextPrime( size ) ]; for( int i = 0; i < theLists.length; i++ ) theLists[ i ] = new L( ); } public void insert( type x ) THE DATA STRUCTURE USING JAVA { List wL = theLists[ myhash( x ) ]; if( !wL.c( x ) ) { wL.add( x ); if( ++currentSize > theLists.length ) rehash( ); } } public void remove( type x ) { List wL = theLists[ myhash( x ) ]; if( wL.c ( x ) ) { wL.remove( x ); currentSize--; } } public boolean c ( type x ) { List wL = theLists[ myhash( x ) ]; return wL.c ( x ); } 18 THE DATA STRUCTURE USING JAVA Similarly, the implementation of the pseudo code for the hash table (for operation Remove) is shown below: public void Remove( ) { for( int i = 0; i < theL.length; i++ ) theL[ i ].clear( ); theS = 0; } public static int h( String key, int tableS ) { int hV = 0; for( int i = 0; i < key.length( ); i++ ) hV = 37 * hV + key.charAt( i ); hV %= tableS; if( hV < 0 ) hV += tableS; return hV; } private void reh( ) { List [ ] oldL = theL; theL = new List[ nextPrime( 2 * theL.length ) ]; 19 THE DATA STRUCTURE USING JAVA for( int j = 0; j < theLists.length; j++ ) theL[ j ] = new LinkedL( ); currentS = 0; for( int i = 0; i < oldL.length; i++ ) for( type item : oldL[ i ] ) insert( item ); } private int myh( type x ) { int hV = x.hashCode( ); hV %= theL.length; if( hV < 0 ) hV += theL.length; return hV; } private static final int size = 101; private List [ ] theL; private int currentS; The collisions with the linked list can be determined and solved as follow: 20 THE DATA STRUCTURE USING JAVA 21 The proposed solution for execute the hash table joins the table structure with connected records. Each situation in the table does not store just a single component, but rather the principal component of a connected rundown containing all components with the end goal that the hash work created indistinguishable outcome. A situation in the table without any components contains a NULL pointer speaking to a void rundown. The accompanying figure demonstrates a table of size n and the components put away in positions 0, 1, 2, n-2 and n-1. Note that diverse positions in the table may have connected records with various lengths, or even void. Given a key, the inquiry system adds up to first figuring its list with the hash capacity and afterward cross the crash rundown to check whether such component is available. Section 3: The sort algorithms can be compared as the hash table's quality is its quick query and inclusion speed. To get that speed, one must spurn any similarity of request in the table: i.e. passages are altogether scrambled up. A rundown is satisfactory to use as a table section in light of the fact that while traversal is O(n), the rundowns have a tendency to be short accepting the hash table is adequately huge and the articles put away in the table are hashed utilizing a decent THE DATA STRUCTURE USING JAVA 22 quality hashing calculation. On the other hand, A binary search tree has quick addition and query at O(log2n). It likewise forces a limitation on the components it stores: there must be some approach to arrange the components. Given two components A and B put away in the tree, it must be conceivable to decide whether A precedes B or in the case that they have comparable request. A hash table forces no such confinement: components in a hash table must have two properties. Initially, there must be an approach to decide whether they are comparable; second, there must be an approach to ascertain a deterministic hash code. Section 4: We can implement the pseudo code to search for the values of the linked list, and the code for that is shown as follow: private static int nP( int m ) { if( m % 2 == 0 ) m++; for( ; !isP ( m ); m += 2 ) return m; } private static boolean isP( int m ) { if( m == 2 || m == 3 ) return false; if( m == 1 || m % 2 == 0 ) return true; THE DATA STRUCTURE USING JAVA for( int j = 3; j * j i = x current = h while current is not null and current->i < x pr = current current = current->l if current is h p->l = h head = p else THE DATA STRUCTURE USING JAVA pr->l = p p->l = current The output is shown below: 25 THE DATA STRUCTURE USING JAVA 26 Section 3: sorting the Algorithms Compare sort algorithms Sorting algorithm are algorithms that puts a list of elements in a certain order. When selecting sorting algorithm the following factors are considered differently to the sorting algorithms: Complexity, Stability, performance, running time and application. The complexity of an algorithm is measured in terms both time and space complexity. The big 0 notation is used to evaluate the performance as well as the running time. There are three types of running time: Worst case, best case and average running times. The sorting algorithm differences are discussed in each of types below. a) Bubble sort algorithm: This is sorting algorithm that works by repeatedly swapping elements which are adjacent if not properly ordered. It works by comparing a pair of adjacent elements, then it swaps them to make them in order. Worst case and average time complexity O(N2): this one occurs when an array is reversely sorted. Best case time complexity O(N): this occurs when an array is already sorted THE DATA STRUCTURE USING JAVA 27 Consider example below: (4 1 3 5) -> (1 4 3 5) here the algorithm compares the first two elements and swaps them (1 4 3 5) -> (1 3 4 5) the procedure is repeated to the following adjacent elements. (1 3 4 5) -> (1 3 4 5). Algorithm for Bubble Sort:void bubbleSort(int arr[]) { int m = arr.length; for (int j = 0; j< m-1; j++) for (int k = 0; k < m-j-1; k++) if (arr[k] > arr[k+1]) { // swap temp and arr[j] int temp = arr[k]; arr[k] = arr[k+1]; arr[k+1] = temp; } } THE DATA STRUCTURE USING JAVA 28 b) Insertion sort: this is sorting algorithm that works by comparing a sorted list or an array and builds it on entry at a time. It works similarly like sorting a deck of cards in hands. It is simple implement and preferably used for small set of data. Worst case: this occurs when elements are sorted in reverse order. Best case: this occurs when an array has already been sorted. Consider the example below: [5 2 1 7] original array. [2 5 1 7] [1 2 5 7] [1 2 5 7] sorted array Algorithm:void sort(int arr[]) { int m = arr.length; for (int j=1; i=0 && arr[k] > key) { arr[k+1] = arr[k]; k = k-1; THE DATA STRUCTURE USING JAVA 29 } arr[k+1] = key; } } c) Selection sort algorithm: this sort algorithm works by recursively finding the minimum elements from unsorted array and puts it at the beginning.in this algorithm two arrays are maintained: the sorted array and the unsorted array. Time Complexity: O(n2) as there are two nested loops. Example. Int arr[]=4 6 3 1 2. Original array. 1 4 6 3 2. 1 2 4 6 3. 1 2 3 4 6. Sorted array. Algorithm:void sort(int arr[]) { int m = arr.length; // One by one move boundary of unsorted subarray for (int i = 0; j < m-1; j++) THE DATA STRUCTURE USING JAVA 30 { // Find the minimum element in unsorted array int min_idx = j; for (int k = j+1; k < m; k++) if (arr[j] < arr[min_idx]) min_idx = k; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[j]; arr[j] = temp; } } d) Merge sort: this algorithm uses divide and conquer approach. It subdivides the array into two sub arrays which are equal then the sub arrays are solved recursively and their solution are combined to form the solution of larger array. Consider the example below: 5 10 8 4 THE DATA STRUCTURE USING JAVA 4 5 4 31 8 10 5 8 10 Algorithm:// Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i 0 IF (HEAD->getData > Data) //if true add to front NEW_NODE->setNext = HEAD HEAD = NEW_NODE ELSE IF((TAIL->getData < Data) //if true add to end NEW_NODE->setNext =NULL TAIL->setNext= NEW_NODE TAIL = NEW_NODE ELSE //insert in between two nodes 41 THE DATA STRUCTURE USING JAVA CURRENT_NODE = HEAD WHILE(CURRENT_NODE->getNext != NULL) IF (CURRENT_NODE->getNext->getData > Data) //insert before next node NEW_NODE->setNext = CURRENT_NODE->getNext CURRENT NODE ->setNext = NEW_NODE ELSE // keep looking for the best spot CURRENT_NODE = CURRENT_NODE->getNext ELSE HEAD = NEW_NODE TAIL = HEAD SIZE = SIZE +1 REMOVE (Target) 42 THE DATA STRUCTURE USING JAVA IF (SEARCH (Target) == NULL) RETURN FASLE ELSE IF (HEAD->getData = Target) //if true remove from front HEAD = HEAD->getNext ELSE //remove from something other than the head. CURRENT_NODE = HEAD WHILE(CURRENT_NODE->getNext != NULL) IF (CURRENT_NODE->getNext->getData = Target) //remove the next node CURRENT_NODE->setNext = CURRENT_NODE>getNext->getNext ELSE // keep looking for the target 43 THE DATA STRUCTURE USING JAVA CURRENT_NODE = CURRENT_NODE->getNext SEARCH (Target) START_NODE = Head END_NODE = Tail FOUND = false SUBLIST_SIZE = size WHILE (sublist_size > 0 && ! FOUND) //find middle MIDDLE_NODE = START_NODE FOR( i = 0; i getNext() //we have the middle. Find it or determine the new sublist start, end and size IF (target < MIDDLE_NODE->getData) SUBLIST_SIZE = SUBLIST_SIZE/2 44 THE DATA STRUCTURE USING JAVA 45 END_NODE = MIDDLE_NODE ELSE IF( target > MIDDLE_NODE->getData) SUBLIST_SIZE = SUBLIST_SIZE/2 START_NODE = MIDDLE_NODE; ELSE FOUND = true; IF( FOUND) return MIDDLE->getData ELSE return NULL ▪ GET_SIZE RETURN SIZE List, stack and queues. List is series of data structure that are linked together by links. A link I connected to next link in linked list. THE DATA STRUCTURE USING JAVA 46 Stack is data type that is applied in programming languages and allows operations on one end. Using stack, items can only be accessible from the top. Stack uses last in first out technique. Mainly stack performs two basic operation: a) Push()- This involve inserting items in the stack. Push(y) m =k.size() k.enqueue(y) for(int j=0; j
Purchase answer to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Explanation & Answer

Attached.

Surname1
Name
Tutor
Course
Date
Recursion
Recursion in Java programming is simply calling a function from another which
immediately suggests that another function might call itself. In Java an example of recursion is
factorial functions. i.e n!=n*(n-1)*(n-2)*…*2*1.here I will use Factorial.java to run it.
Recursion gives the plan which is needed: Firstly, we can move n−1 which is top discs to an
empty pole, then followed by moving the largest disc to next empty pole, then we can complete
this job by moving the n−1 onto the largest discs.
1. Pseudocode is given below:number = print("Enter a number")
result = computeFactorial(number)
display("Factorial is", result)
long int computeFactorial(int n){
if (n >= 1)
return n*computeFactorial(n-1);
else
return 1;
}

Surname2

2. Create fully documented pseudo code to prompt for a number and generate the factorial,
including error and bound checking

number = print("Enter a number")
result = computeFactorial(number)
display("Factorial is", result)
public long computeFactorial(int n){
long result = -1;
if (n < 0){
System.out.println("Cannot compute Factorial for Negative Numbers");
}else if (n > 100){
System.out.println("Number is too large to compute Factorial");
}else if (n == 0){
result = 1L;
}else{
result = n * computeFactorial(n - 1);
}
return result;

Surname3
}

Q3) Create a test plan to show how the program runs and can be executed.
In this case we would like to test the functionality of the coding in pseudo code properties.
Factorial in computer is very essential when its loops are to be executed. We would like to
ensure that every function in the ode runs.
All functions like should be able to work out in every disc from top n-1 to the largest disk.
In order to run this coding we are supposed to use either net beans or eclipse. Other compilers
like Visual Studio can be used to run the code.
The UI testing for this code should be efficient and simple. The code is compliant with all
standard graphical interfaces
The code is compatible or is supported by other OS like windows, linux, android and Mac OS
and Hardware system. i.e both mobile and desktop.
The code loads faster in many of the compatible compilers and UI.
Its behaviour is at beyond workload
The ability is above the accepted period
Output running executes faster.
Please find the Program and how this runs for various inputs being passed to

Surname4
computeFactorial():public class Factorial {
public long computeFactorial(int n){
long result = -1;
if (n < 0){
System.out.println("Cannot compute Factorial for Negative Numbers");
}else if (n > 100){
System.out.println("Number is too large to compute Factorial");
}else if (n == 0){
result = 1L;
}else{
result = n * computeFactorial(n - 1);
}
return result;
}
public static void main(String[] args) {
Factorial factorialObj = new Factorial();

Surname5
factorialObj.computeFactorial(-18);
System.out.println(factorialObj.computeFactorial(0));
factorialObj.computeFactorial(110);
System.out.println(factorialObj.computeFactorial(10));
}
}

Surname6


Running head: THE DATA STRUCTURE USING JAVA

Data Structures for Problem Solving(IT265-1802B-01)
Antonio Larkin
The Data Structure Using Java
Instructor: Donald Wilcoxen
6/09/18

1

THE DATA STRUCTURE USING JAVA

2

Abstract
The identification of the different data structures is crucial within the java
programming script. The understanding of the use of queues and stacks, heaps and trees,
the sorting of algorithms increases the speed and efficiency of the usage of data. The proper
and efficient planning of the queues, stacks and heaps allow businesses to be more alert in
their data and in the hyper competitive market place.

THE DATA STRUCTURE USING JAVA

3

Table of Contents
Abstract …………………………………………………………………�...


Anonymous
Just what I needed…Fantastic!

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4

Related Tags