Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Data Structure Exercise Lab Book for CS102 Last modified: October 31, 2015 By Professor Jeongkyu Lee, PhD Contents Exercise Lab 0: Installing and Using NetBeans .............................................................................................. 4 Installing NetBeans ................................................................................................................................... 4 After it is fully installed, create a project “HelloWorld” ........................................................................... 5 Exploring the IDE ....................................................................................................................................... 7 Exercise Lab 1: Java Review .......................................................................................................................... 8 Defining Class ............................................................................................................................................ 8 Objects That Contain Objects ................................................................................................................... 8 Class that Extend Classes and Inheritance ................................................................................................ 9 Exercise Lab 2: Array ................................................................................................................................... 11 Telephone Information Directory Application ........................................................................................ 11 Node Definition Class .............................................................................................................................. 11 Data Structure Class ................................................................................................................................ 12 Application Program ............................................................................................................................... 13 Exercise Lab 3.1: Stack ................................................................................................................................ 15 Implementation of Classical Stack Structure .......................................................................................... 15 Node Definition Class .............................................................................................................................. 15 Data Structure Class ................................................................................................................................ 15 Application Program ............................................................................................................................... 16 Exercise Lab 3.2: Queue .............................................................................................................................. 19 Implementation of Classical Queue Structure ........................................................................................ 19 Data Structure Class ................................................................................................................................ 19 Application Program ............................................................................................................................... 20 Exercise Lab 4: Linked Lists ......................................................................................................................... 22 Implementation of the Singly Linked List................................................................................................ 22 Data Structure Class ................................................................................................................................ 22 Application Program ............................................................................................................................... 23 Exercise Lab 5: Hash .................................................................................................................................... 25 The Linear Quotient (LQHashed) Data Structure Implementation ......................................................... 25 Data Structure Class ................................................................................................................................ 25 Application Program ............................................................................................................................... 28 Exercise Lab 6: Recursion ............................................................................................................................ 30 n Factorial ............................................................................................................................................... 30 Tracing a Recursive Method’s Execution Path ........................................................................................ 30 Fibonacci Sequence................................................................................................................................. 31 Exercise Lab 7: Trees ................................................................................................................................... 33 Implementing Binary Search Tree........................................................................................................... 33 Data Structure Class ................................................................................................................................ 33 Node Class ............................................................................................................................................... 36 Application Program ............................................................................................................................... 36 Exercise Lab 8:Sorting ................................................................................................................................. 38 Merge Sort .............................................................................................................................................. 38 Quick Sort ................................................................................................................................................ 39 Application Program ............................................................................................................................... 40 Exercise Lab 9: Graph .................................................................................................................................. 41 Simple Directed Graph ............................................................................................................................ 41 Node Structure........................................................................................................................................ 41 Airline Hub Application Program ............................................................................................................ 42 Exercise Lab 0: Installing and Using NetBeans In this exercise lab, you will gain structured insights into the key features that NetBeans IDE makes available, all for free. Starting from installation and your first “hello world” application in Java, you will travel through basic key feature of the IDE, whether you are just beginning to learn Java or want to be productive in Java enterprise environments. Installing NetBeans 1. Download and install from this link: http://www.oracle.com/technetwork/java/javase/downloads/jdk-7-netbeans-download432126.html 2. On that link, pick the version that belongs to your computer For windows users: X86 means Windows 32 bit, x64 means windows 64 bit. If you are not sure which one you have, right-click the “My computer” icon → Properties and look under System type: After it is fully installed, create a project “HelloWorld” 1. Open the program top left click on File New Project 2. In the project wizard select Java Java Application 3. Do the following three things: a. Give it a project name (name should start with capital letter) b. pick a project location ( this will be where all your projects will reside) c. Check “create main class” and give it a name d. Check “set as main project” 4. In the Create Main Class field, change helloworld.HelloWorld to com.mydomain.myproject.HelloWorld. When you enter a fully-qualified class name in this field, the IDE will generate directories for each level of the package structure when you complete this process. Click Finish. 5. Replace // TODO code application logic by System.out.println("Hello World!"); 6. Save the file (Ctrl + S or File → Save) 7. Press F11 or Choose Run → Build Main Project to Compile and Package the application 8. Open Output Window: Window → Output 9. Press F6 (or choose Run ➤ Run Main Project) to run the project. Exploring the IDE 1. Project View The Projects window (Ctrl+1) is the main entry point to your project sources. It shows a logical view of the important project content; that is, it shows you the files you are most likely to want to work with, organized in folders that you are likely to easily understand. Together with the Projects window, the IDE provides the Files window (Ctrl+2), so that you can see all the files that belong to a project. A third project view is provided by the Favorites window (Ctrl+3). The Favorites window gives you access to all the folders and files on disk. 2. File View The Navigator window (Ctrl+7) provides a compact view of the currently selected file and simplifies navigation between different parts of the file. 3. Hierarchy View The Hierarchy window (Alt+F12) displays the supertypes and subtypes of the currently selected Java file or the currently selected Java type under the cursor in the editor. 4. Service View The Services window (Ctrl+5) gives you access to many ancillary resources, such as databases, servers, web services, and issue trackers. 5. Supporting View The windows available to support the project views, file views, and service views are the Output window, Properties window, Action Items window, Tasks window, and Notifications window. Properties Window The Properties window (Ctrl+Shift+7) displays the properties of the currently selected item. For example, most items that can be represented in the Projects, Files, or Navigator windows have properties that can be viewed in the Properties window. Exercise Lab 1: Java Review Defining Class Class name: Person Description: A class named Person that contains two data members, age and weight Source: Person.java public class Person { // definition of the data members private int age; private double weight; // definition of member functions public Person(int a, double w ) // the constructor { age = a; weight = w; } // end of constructor public String toString( ) // returns annotated value of data members { return( "this person’s age is: " + age + "\nand their weight is: " + weight); } // end of toString method } // end of Person class Objects That Contain Objects Class name: WeightLossClass Description: Initialize the weight and height of each person and be able to output their data. Source: WeightLossClass.java public class WeightLossClass { // data members private Person person1, person2, person3; // three Person reference variables // methods public WeightLossClass(int a1, double w1, int a2, double w2, int a3, double w3) { person1 = new Person(a1, w1); // allocation of three Person objects person2 = new Person(a2, w2); person3 = new Person(a3, w3); }// end of constructor public void showAll ( ) { System.out.println(person1.toString( )); System.out.println(person2.toString( )); System.out.println(person3.toString( )); }// end of showAll method }// end of class weightLossStudent Driver Program Class name: WeightLossDriver Description: create two of WeightLossClass with the statement and show all. WeightLossClass class1 = new WeightLossClass (21, 300.1, 54, 250.2, 32, 400.3); WeightLossClass class2 = new WeightLossClass (63, 195.4, 38, 160.5, 73, 195.6); Source: WeightLossDriver.java public class WeightLossDriver { /** * @param args the command line arguments */ public static void main(String[] args) { WeightLossClass class1 = new WeightLossClass (21, 300.1, 54, 250.2, 32, 400.3); WeightLossClass class2 = new WeightLossClass (63, 195.4, 38, 160.5, 73, 195.6); class1.showAll(); class2.showAll(); } } Class that Extend Classes and Inheritance Class name: WeightLossClient Description: all the data members and methods of the Person class as well as the new data members, goal weight. And, it would contain a constructor and a toString method to accommodate the additional data member. Source: WeightLossClient public class WeightLossClient extends Person { // member data private double goalWeight; // member methods public WeightLossClient( int a, double w, double g) { super(a,w); // initializes the age and weight , the inherited attributes goalWeight = g; } public String toString( ) { String s = super.toString( ); // invokes the inherited toString method for age and weight return ( s + "\nand the person’s goal weight is: " + goalWeight); } } Class name: WeightLossClassRevised Description: Revise WeightLossClass. Person is replaced by WeightLossClient, and the class’ constructor is expanded to process the goal weight. Source: WeightLossClassRevised.java public class WeightLossClassRevised { // data members private WeightLossClient person1, person2, person3; // three WeightLossClient reference variables // methods public WeightLossClassRevised(int a1, double w1, int a2, double w2, int a3, double w3, { person1 = new WeightLossClient (a1, w1, g1); person2 = new WeightLossClient (a2, w2, g2); objects person3 = new WeightLossClient (a3, w3, g3); } public void showAll( ) { System.out.println(person1.toString( )); System.out.println(person2.toString( )); System.out.println(person3.toString( )); }// end of showAll method } double g1, double g2, double g3) // allocation of three // WeightLossClient Modify WeightLossDriver by creating class1 object: WeightLossClassRevised class3 = new WeightLossClassRevised(21, 189.5, 150, 33, 160.0, 121.0, 40, 190.2, 175.0); Exercise Lab 2: Array Telephone Information Directory Application Objective: Implementation of the Unsorted-Optimized Array Structure. Requirements: 1. A three-parameter constructor to create a node Name (15 bytes) + Address (28 bytes) + Number (7 bytes) 2. toString method to return the annotated contents of a node 3. deepCopy method (used by the data structure to maintain encapsulation) 4. A method to compare a given key to the contents of the name field of a node 5. A method to set the value of a node’s address field Node Definition Class Class name: Listing Description: Define the telephone directory node Source: Listing.java package ex2; /** * * @author Jeongkyu */ public class Listing { private String name; // key field private String address; private String number; public Listing(String n, String a, String num ) { name = n; address = a; number = num; } public String toString( ) { return("Name is " + name + "\nAddress is " + address + "\nNumber is " + number + "\n"); } public Listing deepCopy( ) { Listing clone = new Listing(name, address, number); return clone; } public int compareTo(String targetKey) { return(name.compareTo(targetKey)); } public void setAddress(String a) // coded to demonstrate encapsulation { address = a; } }// end of class Listing Data Structure Class Class name: UnsortedOptimizedArray Description: Source: UnsortedOptimizedArray.java package ex2; /** * * @author Jeongkyu */ public class UnsortedOptimizedArray { private int next; private int size; private Listing[ ] data; public UnsortedOptimizedArray( ) { next = 0; size = 100; data = new Listing[size]; }//end of constructor public boolean insert(Listing newNode) { if(next >= size) // the structure is full return false; data[next]= newNode.deepCopy( ); // store a deep copy of the client’s node if(data[next] == null) // insufficient system memory return false; next = next + 1; // prepare for the next insert return true; }// end of insert method public Listing fetch(String targetKey) { Listing node; Listing temp; // access the node using a sequential search int i = 0; while ( i < next && !(data[i].compareTo(targetKey) == 0)) { i++; } if(i== next) // node not found return null; //deep copy the node's information into the client's node node = data[i].deepCopy( ); // move the node up one position in the array, unless it is the first node { if(i != 0) // bubble-up accessed node temp = data[i-1]; data[i-1] = data[i]; data[i] = temp; } return node; } // end of fetch method public boolean delete(String targetKey) {// access the node using a sequential search int i = 0; while (i < next && !(data[i].compareTo(targetKey) == 0)) { i++; } if(i == next) // node not found return false; //move the last node into the deleted node's position data[ i] = data[ next -1]; data[next-1] = null; next = next - 1; return true; // node found and deleted }//end of the delete method public boolean update(String targetKey, Listing newNode) if(delete(targetKey) == false) // node not in the structure return false; else if( insert(newNode ) == false) // insufficient memory return false; else return true; // node found and updated }// end of update method }//end of class UnsortedOptimizedArray { Application Program Class name: MainUnsortedOptimizedArray Description: Demonstrate the use of UnsortedOPtimizedArray. Source: MainUnsortedOptimizedArray.java package ex2; /** * * @author Jeongkyu */ public class MainUnsortedOptimizedArray { public static void main(String[] args) { UnsortedOptimizedArray boston = new UnsortedOptimizedArray( ); Listing temp; // Test of the constructor Listing bill = new Listing("Bill", "First Avenue", "345 7474"); Listing mary = new Listing("Mary", "Second Avenue", "123 4567"); Listing tom = new Listing("Tom", "Third Avenue", "999 9999"); // Test of the insert and fetch methods. Outputs true, true, null, Bill and Mary System.out.println("*** Test of the insert and fetch methods ***"); System.out.println(boston.insert(bill)); System.out.println(boston.insert(mary)); System.out.println(boston.fetch("Tom")); temp = boston.fetch("Bill"); System.out.println(temp.toString()); temp = boston.fetch("Mary"); System.out.println(temp.toString( )); // Test of encapsulation. Output Mary’s new listing, then the encapsulated listing System.out.println("*** Test of the data encapsulation ***"); mary.setAddress("Ninth Avenue"); // will not change the data structure listing System.out.println(mary.toString( )); temp = boston.fetch("Mary"); System.out.println(temp.toString( )); // Test of the Delete method. Next three outputs should be false, true and null System.out.println("*** Test of the delete method ***"); System.out.println(boston.delete("Tom")); System.out.println(boston.delete("Bill")); System.out.println(boston.fetch("Bill")); // Test of the Update method. Output should be false, true, null, Tom System.out.println("\n*** Test of the update method ***"); System.out.println(boston.update("tom", mary)); boston.insert(bill); System.out.println(boston.update("Bill", tom)); System.out.println(boston.fetch("Bill")); temp = boston.fetch("Tom"); System.out.println(temp.toString( )); System.exit(0); } } Exercise Lab 3.1: Stack Implementation of Classical Stack Structure Objective: The implementation of the classical Stack structure Requirements: 1. Homogeneous, fully encapsulated structure that stores Listing object 2. Method push 3. Method pop 4. Method showAll Node Definition Class Class name: Listing Description: Define the nodes to be stored on the stack. It provides a method to deep copy a node (i.e., deepCopy), and a toString method. Source: Listing.java package ex3; /** * * @author Jeongkyu */ public class Listing { private String name; private String address; private String number; public Listing() { name = ""; address = ""; number = ""; } public Listing(String n, String a, String num ) { name = n; address = a; number = num; } public String toString( ) { return ("Name is " + name + '\n' + "Address is " + address + '\n' + "Number is " + number + '\n'); } public Listing deepCopy( ) { Listing clone = new Listing(name, address, number); return clone; } } Data Structure Class Class name: Stack Description: Homogeneous, fully encapsulated structure that stores Listing object Source: Stack.java package ex3; /** * * @author Jeongkyu */ public class Stack { private Listing[] data; private int top; private int size; public Stack( ) { top = -1; size = 100; data = new Listing[100]; } public Stack(int n) { top = -1; size = n; data = new Listing[n]; } public boolean push(Listing newNode) { if(top == size-1) return false; // ** overflow error ** else { top = top +1; data[top] = newNode.deepCopy(); return true; // push operation successful } } public Listing pop( ) { int topLocation; if(top == -1) return null; // ** underflow error ** else { topLocation = top; top = top -1; return data[topLocation]; } } public void showAll( ) { for(int i = top; i >= 0; i--) System.out.println(data[i].toString()); } } Application Program Class name: MainStack Description: Demonstrate the use of the class Stack Source: MainStack.java package ex3; public class MainStack { public static void main(String[] args) { Stack s = new Stack(3); Listing l; Listing l1 = new Listing("Bill", "1st Avenue", "123 4567"); Listing l2 = new Listing("Al", "2nd Avenue", "456 3232"); Listing l3 = new Listing("Mike", "3rd Avenue", "333 3333"); Listing l4 = new Listing("Carol", "4th Avenue", "444 4444"); // an attempt to perform a pop on an initialized (empty) stack will return null System.out.println(s.pop()); // perform three pushes to fill the stack and then output the stack System.out.println(s.push(l1)); System.out.println(s.push(l2)); System.out.println(s.push(l3)); s.showAll(); // perform three pop operations to empty the stack l = s.pop(); System.out.println(l.toString()); l = s.pop(); System.out.println(l.toString()); l = s.pop(); System.out.println(l.toString()); // an attempt to perform a pop on an empty stack will return null l = s.pop(); System.out.println(l); System.exit(0); } } Exercise Lab 3.2: Queue Implementation of Classical Queue Structure Objective: The implementation of the classical Queue structure Requirements: 1. Homogeneous, fully encapsulated structure that stores Listing object 2. Two constructor: one is a default constructor that allows a max of 100 nodes, and another includes an integer parameter n that allows the client to specify the max number of nodes. 3. Method enque 4. Method deque 5. Method showAll Data Structure Class Class name: Queue Description: Homogeneous, fully encapsulated structure that stores Listing object Source: Queue.java package ex3; /** * * @author Jeongkyu */ public class Queue { private Listing[] data; private int size; private int numOfNodes; private int front; private int rear; public Queue() { size = 100; numOfNodes = 0; front = 0; rear = 0; data = new Listing[100]; } public Queue(int n) { size = n; numOfNodes = 0; front = 0; rear = 0; data = new Listing[n]; } public boolean enque(Listing newNode) { if(numOfNodes == size) return false; // ** overflow error ** else { numOfNodes = numOfNodes +1; data[rear] = newNode.deepCopy(); rear = (rear +1) % size; return true; // push operation successful } } public Listing deque( ) { int frontLocation; if(numOfNodes == 0) return null; // ** underflow error ** else { frontLocation = front; front = (front + 1) % size; numOfNodes = numOfNodes -1; return data[frontLocation]; } } public void showAll() { int i = front; for(int c = 1; c <= numOfNodes; c++) { System.out.println(data[i].toString( )); i = (i + 1) % size; } } } Application Program Class name: MainQueue Description: Demonstrate the use of the class Queue Source: MainQueue.java package ex3; public class MainQueue { public static void main(String[] args) { Queue q = new Queue(3); Listing l; Listing l1 = new Listing("Bill", "1st Avenue", "123 4567" ); Listing l2 = new Listing("Al", "2nd Avenue", "456 3232"); Listing l3 = new Listing("Mike", "3rd Avenue", "333 3333"); Listing l4 = new Listing("Carol", "4th Avenue", "444 4444"); // an attempt to perform a dequeue on an initialized (empty) queue will return null System.out.println(q.deque()); // perform three enqueue to fill the queue and then output the queue System.out.println(q.enque(l1)); System.out.println(q.enque(l2)); System.out.println(q.enque(l3)); System.out.println(q.enque(l4)); q.showAll(); // perform three dequeue operations to empty the queue l = q.deque(); System.out.println(l.toString( )); l = q.deque(); System.out.println(l.toString( )); l = q.deque(); System.out.println(l.toString( )); // an attempt to perform a dequeue on an empty queue will return null l = q.deque(); System.out.println(l); System.exit(0); } } Exercise Lab 4: Linked Lists Implementation of the Singly Linked List Objective: Implementing a homogeneous, fully encapsulated singly linked list structure Requirements: 1. Generic use of Listing in Exercise Lab 2 2. Method insert 3. Method fetch 4. Method delete 5. Method update 6. Method showAll Data Structure Class Class name: SinglyLinkedList Description: Implementing a homogeneous, fully encapsulated singly linked list structure Source: SinglyLinkedList.java public class SinglyLinkedList { private Node h; // list header public SinglyLinkedList() { h = new Node(); // dummy node h.l = null; h.next = null; } public boolean insert(Listing newListing) { Node n = new Node(); if(n == null) // out of memory return false; else { n.next = h.next; h.next = n; n.l = newListing.deepCopy(); return true; } } public Listing fetch(String targetKey) { Node p = h.next; while (p != null && !(p.l.compareTo(targetKey) == 0)) { p = p.next; } if(p != null) return p.l.deepCopy(); else return null; } public boolean delete(String targetKey) { Node q = h; Node p = h.next; while (p != null && !(p.l.compareTo(targetKey) == 0)) { q = p; p = p.next; } if(p != null) { q.next = p.next; return true; } else return false; } public boolean update(String targetKey, Listing newListing) { if(delete(targetKey) == false) return false; else if(insert(newListing) == false) return false; return true; } public void showAll() { Node p = h.next; while (p != null) //continue to traverse the list { System.out.println(p.l.toString( )); p = p.next; } } public class Node { private Listing l; private Node next; public Node() { } }// end of inner class Node }//end SinglyLinkedList outer class ** Note that Listing class is the same class as in Exercise Lab 2. Application Program Class name: MainSinglyLinkedList Description: Demonstrate the use of the class Singly linked list Source: MainSinglyLinkedList.java package ex4; /** * * @author Jeongkyu */ public class MainSinglyLinkedListStack { public static void main(String[] args) { SinglyLinkedList boston = new SinglyLinkedList(); Listing l1 = new Listing("X", "1st Avenue", "123 4567" ); Listing l2 = new Listing("X", "2nd Avenue", "456 3232"); Listing l3 = new Listing("X", "3rd Avenue", "333 3333"); // three “push” operations boston.insert(l1); boston.insert(l2); boston.insert(l3); //Three “pop” operations l3 = boston.fetch("X"); // first “pop” boston.delete("X"); System.out.println(l3); // (Java automatically invokes the toString method) l3 = boston.fetch("X"); // second “pop” boston.delete("X"); System.out.println(l3); // (Java automatically invokes the toString method) l3 = boston.fetch("X"); // third “pop” boston.delete("X"); System.out.println(l3); // System.exit(0); } } Exercise Lab 5: Hash The Linear Quotient (LQHashed) Data Structure Implementation Objective: Implementing a hashed data structure, i.e., LQHashed Requirements: 1. Keys are assumed to be strings of any length 2. Method: stringToInt for preprocessing that maps keys to numeric pseudo keys 3. Method: fourKPlus3 for max number of nodes to be stored. In this, set the optimum loading factor = 0.75 4. The range of pseudo keys: 0 to 2,147,483,648 (32 bit signed integer) 5. Division Hashing algorithm will be used to map the pseudo keys into indices 6. The default quotient = k4+3 prime, i.e., 9967 7. Method: insert 8. Method: fetch 9. Method: delete 10. Method: update 11. Method: showAll Data Structure Class Class name: LqHashed Description: a fully encapsulated homogeneous implementation of a hashed data structure Source: LqHashed.java public class LqHashed { int N; int n = 0; // the number of nodes in the structure int defaultQuotient = 9967; // the default 4k+3 prime double loadingFactor = 0.75; Listing deleted; // the dummy node, v2 private Listing[] data; // the primary storage array public LqHashed(int length) { int pct = (int)((1.0/loadingFactor-1) *100.0); N = fourKPlus3(length, pct); data = new Listing[N]; deleted = new Listing("","",""); for(int i = 0; i<N; i++) data[i] = null; }// end of constructor public boolean insert(Listing newListing) { boolean noError; boolean hit = false; int pass, q, offset, ip; int pk = stringToInt(newListing.getKey()); // preprocess the key if( (((double) n)/N) < loadingFactor)// insert the node { pass = 0; q = pk / N; offset = q; ip = pk % N; if(q%N == 0) offset = defaultQuotient; while(pass < N) { if(data[ip] == null || data[ip] == deleted) { hit = true; break; } ip = (ip + offset)%N; pass = pass +1; } if(hit == true) // insert the node { data[ip]=newListing.deepCopy( ); n++; return noError = true; } else return noError = false; } else //structure full to loading factor return noError = false; }// end for the Insert method public Listing fetch(String targetKey) { boolean noError; boolean hit = false; int pass, q, offset, ip; int pk = stringToInt(targetKey); // preprocess the key pass = 0; q = pk / N; offset = q ; ip = pk % N; if(q%N == 0) offset = defaultQuotient; while(pass < N) { if(data[ip] == null) //node not in structure break; if(data[ip].compareTo(targetKey) == 0) //node found { hit = true; break; } ip = (ip + offset)%N; //collision occurred pass = pass +1; } if(hit == true) //return a deep copy of the node return data[ip].deepCopy( ); else return null; }//end of the Fetch method public boolean delete(String targetKey) { boolean noError; boolean hit = false; int pass, q, offset, ip; int pk = stringToInt(targetKey); // preprocess the key pass = 0; q = pk / N; offset = q; ip = pk % N; if(q%N == 0) offset = defaultQuotient; while(pass < N) { if(data[ip] == null) //node not in structure break; if(data[ip].compareTo(targetKey) == 0) // node found { hit = true; break; } ip = (ip + offset)%N; //collision occurred pass = pass +1; } if(hit == true) //delete the node { data[ip] = deleted; n--; return noError = true; } else return noError = false; }//end of the Delete method public boolean update(String targetKey, Listing newListing) { if(delete(targetKey) == false) return false; else if(insert(newListing) == false) return false; return true; }//end of the Update method public void showAll() { for(int i= 0; i<N; i++) if(data[i] != null && data[i] != deleted) data[i].toString(); } public static int fourKPlus3(int n, int pct) // from Figure 5.16 { boolean fkp3 = false; boolean aPrime = false; int prime, highDivisor, d; double pctd = pct; prime = (int)(n * (1.0 + (pctd/100.0))); // guess the prime pct percent larger than n if(prime%2 == 0) //if even make the prime guess odd prime = prime +1; while(fkp3 == false) // not a 4k+3 prime { while(aPrime == false) // not a prime { highDivisor = (int)(Math.sqrt(prime) + 0.5); for(d = highDivisor; d > 1; d--) { if(prime%d == 0) break; } if(d != 1) // prime not found prime = prime +2; else aPrime = true; }// end of the prime search loop if((prime-3)%4 == 0) fkp3 = true; else { prime = prime +2; aPrime = false; } }// end of 4k+3 prime search loop return prime; } public static int stringToInt(String aKey) // from Figure 5.18 { int pseudoKey = 0; int n = 1; int cn= 0; char c[] = aKey.toCharArray(); int grouping =0; while (cn < aKey.length()) // there is still more character in the key { grouping = grouping << 8; // pack next four characters in i grouping = grouping + c[cn]; cn = cn + 1; if (n==4 || cn == aKey.length()) // 4 characters are processed or no more characters { pseudoKey = pseudoKey + grouping; n = 0; grouping = 0; } n = n + 1; } return Math.abs(pseudoKey); } } ** Note that Listing class is the same class as in Exercise Lab 2. Application Program Class name: MainLqHashed Description: Demonstrate the used of LqHashed Source: MainLqHashed.java public class MainLqHashed { public static void main(String[] args) { LqHashed dataBase = new LqHashed(100); Listing b, t; Listing bill = new Listing("Bill", "1st Avenue", "999 9999"); Listing tom = new Listing("Tom", "2nd Avenue", "456 8978"); Listing newBill = new Listing("William", "99th Street", "123 4567"); // inserts dataBase.insert(bill); dataBase.insert(tom); // fetches b = dataBase.fetch("Bill"); t = dataBase.fetch("Tom"); System.out.println(b); System.out.println(t); // update of Bill's address dataBase.update("Bill", newBill); b = dataBase.fetch("William"); //fetches System.out.println(b); // demonstration of encapsulation. Client can not change the contents of the node newBill.setAddress("18 Park Avenue"); b = dataBase.fetch("William"); System.out.println(b); // delete operation dataBase.delete("William"); b = dataBase.fetch("William"); System.out.println(b); } } Exercise Lab 6: Recursion n Factorial Class name: Factorial Description: Implementation of n factorial using recursion Source: Factorial.java public class Factorial { public static long nFactorial(long n) { long nMinus1Factorial; if(n == 0) return ( 1 ); else { nMinus1Factorial = nFactorial(n-1); return ( n * nMinus1Factorial); } } } Class name: MainFactorial Description: the recursive use of Factorial (when n = 4) Source: MainFactorail.java public class MainFactorial { public static void main(String[] args) { long n = 4; System.out.println(n + " factorial is " + Factorial.nFactorial(n)); } } Tracing a Recursive Method’s Execution Path Class name: FactorialTrace Description: Implementation of n factorial using recursion with tracing the execution path Source: FactorialTrace.java public class FactorialTrace { public static int count = 0; public static int time = 0; public static long nFactorialTrace(long n) { long value; count ++; time ++; System.out.println("at time " + time); System.out.println("\tnFactorial has been INVOKED for the " + count + "th time," + " with n = to " + n ); if(n == 0) { time++; System.out.println("\nat time " + time); System.out.println("\tRETURNING 0! = 1" + " from the " + count-- + "th invocation of nFactorial"); return 1; } else { System.out.println("\tnFractorial is INVOKING ITSELF with n = to " + (n1)); value = n*nFactorialTrace(n-1); time ++; System.out.println("at time " + time); System.out.println("\tRETURNING " + n + "! = " + value + " from the " + count-- + "th invocation of nFactorial"); return value; } }//end of the method nFactorialTrace }// end of the class Class name: MainFactorialTrace Description: the recursive use of FactorialTrace (when n = 4) Source: MainFactorialTrace.java public class MainFactorialTrace { public static void main(String[] args) { long n = 4; System.out.println(n + " factorial is " + FactorialTrace.nFactorialTrace(n)); } } Fibonacci Sequence Class name: MainFibonacciTerms Description: Implementation of n-th term of the Fibonacci Sequence using recursion Source: MainFibonacciTerms.java public class MainFibonacciTerms { public static void main(String[] args) { int lastTerm = 45; for (int i=1; i<=lastTerm; i++) { System.out.println(" fibonacci" + i + " " + fibonacci(i)); } }// end main { public static long fibonacci(int n) if(n == 1 || n == 2) //one of 2 base cases return 1; else { long rp1 = fibonacci(n-1); // first reduced problem long rp2 = fibonacci(n-2); // second reduced problem long gs = rp1 + rp2; // general solution return gs; } }// end fibonacci method }// end MainFibonacciTerms class Exercise Lab 7: Trees Implementing Binary Search Tree Objective: Implementing BinaryTree which is a fully encapsulated homogeneous implementation of a binary search tree structure. Requirements: 1. Generic use of Listing in Exercise Lab 2 2. Listing class has (i) deepCopy method, (ii) compareTo method, and (iii) getKey method 3. TreeNode class: define the objects that will make up the binary search tree including three reference variables: node: Listing objects lc: TreeNode rc: TreeNode 4. Method: insert 5. Method: fetch 6. Method: delete 7. Method: update 8. Method: findNode (iterative pseudocode version of the algorithm) 9. Class: TreeNodeWrapper Data Structure Class Class name: BinaryTree Description: implementation of binary search tree Source: BinaryTree.java public class BinaryTree { TreeNode root; public BinaryTree() { root = null; } public boolean insert(Listing newListing) { TreeNodeWrapper p = new TreeNodeWrapper(); TreeNodeWrapper c = new TreeNodeWrapper(); TreeNode n = new TreeNode(); if(n == null) // out of memory return false; else // insert the node { n.node = newListing.deepCopy(); // copy the node as a leaf node n.lc = null; n.rc = null; if(root == null) // tree is empty { root = n; } else { findNode(newListing.getKey(), p, c ); // find the new node's parent if(newListing.getKey().compareTo(p.get().node.getKey( )) < 0) // insert at right p.get().lc = n; else p.get().rc = n; } return true; } } //end insert method public Listing fetch(String targetKey) { boolean found; TreeNodeWrapper p = new TreeNodeWrapper(); TreeNodeWrapper c = new TreeNodeWrapper(); found = findNode(targetKey, p, c); // insert the new leaf node if(found == true) return c.get().node.deepCopy(); else return null; }// end of fetch method public boolean delete(String targetKey) { boolean found; TreeNodeWrapper p = new TreeNodeWrapper(); TreeNodeWrapper c = new TreeNodeWrapper(); TreeNode largest; TreeNode nextLargest; found = findNode(targetKey, p, c); if(found == false) // node not found return false; else { if(c.get().lc == null && c.get().rc == null) // case 1: deleted node has no children { if(p.get().lc == c.get()) // deleted node is a left child p.get().lc = null; else // deleted node is a right child p.get().rc = null; }// end case 1 else if(c.get().lc == null || c.get().rc == null) // case 2: delete node has one child { if(p.get().lc == c.get()) //deleted node is a left child { if(c.get().lc != null) // deleted node has a left child p.get().lc = c.get().lc; else p.get().lc = c.get().rc; } else // deleted node is a right child { if(c.get().lc != null) // deleted node has a left child p.get().rc = c.get().lc; else p.get().rc = c.get().rc; } }// end case 2 else // case 3: deleted node has two children { nextLargest = c.get().lc; largest = nextLargest.rc; if(largest != null) // left child of deleted node has a right subtree { while(largest.rc != null) // move down the right edge of right subtree { nextLargest = largest; largest = largest.rc; } c.get().node = largest.node; // "copy" largest node's info into deleted node nextLargest.rc = largest.lc; // save left subtree of largest node } else // left child of deleted node does not have a right subtree { nextLargest.rc = c.get().rc; // save the right subtree of the deleted node if(p.get().lc == c.get()) //deleted node is a left child p.get().lc = nextLargest; // deleted node's parent jumps around deleted node else // deleted node is a right child p.get().rc = nextLargest; // deleted node's parent jumps around deleted node } }// end of case 3 return true; } }// end of delete method public boolean update(String targetKey, Listing newListing) { if(delete(targetKey) == false) return false; else if(insert(newListing) == false) return false; return true; }//end of update public class TreeNode { private Listing node; private TreeNode lc; private TreeNode rc; public TreeNode() { } }// end of class TreeNode private boolean findNode(String targetKey, TreeNodeWrapper parent, TreeNodeWrapper child) { parent.set(root); child.set(root); if(root == null) // tree is empty return true; while(child.get( ) != null) { if(child.get( ).node.compareTo(targetKey) == 0) // node found return true; else { parent.set(child.get( )); if(targetKey.compareTo(child.get( ).node.getKey( )) < 0) child.set(child.get( ).lc); else child.set(child.get( ).rc); } }// end while return false; } // end of findNode public class TreeNodeWrapper { TreeNode treeRef = null; public TreeNodeWrapper() { } public TreeNode get() { return treeRef; } public void set(TreeNode t) { treeRef = t; } }// end of class TreeNodeWrapper }//end class BinaryTree Node Class ** Note that Listing class is the same class as in Exercise Lab 2. public class Listing { private String name; // key field private String address; private String number; public Listing(String n, String a, String num ) { name = n; address = a; number = num; } public String toString( ) { return("Name is " + name + "\nAddress is " + address + "\nNumber is " + number + "\n"); } public Listing deepCopy( ) { Listing clone = new Listing(name, address, number); return clone; } public int compareTo(String targetKey) { return(name.compareTo(targetKey)); } public void setAddress(String a) // coded to demonstrate encapsulation { address = a; } public String getKey() { return name; } }// end of class Listing Application Program Class name: MainBinaryTree Description: the use of BinaryTree Source: MainBinaryTree.java public class MainBinaryTree {public static void main(String[] args) {BinaryTree t = new BinaryTree(); Listing l; Listing l1 = new Listing("Ann", "1st Avenue", "111 1111"); Listing l2 = new Listing("Bill", "2nd Avenue", "222 2222" ); Listing l3 = new Listing("Carol", "3rd Avenue", "333 3333"); Listing l4 = new Listing("Mike", "4th Avenue", "444 4444"); Listing l5 = new Listing("Pat", "5th Avenue", "555 5555"); Listing l6 = new Listing("Sally", "6th Avenue", "666 6666"); Listing l7 = new Listing("Ted", "7th Avenue", "777 7777"); Listing l8 = new Listing("Vick", "8th Avenue", "888 8888"); Listing l9 = new Listing("Will", "9th Avenue", "999 9999"); Listing l10 = new Listing("Zack", "11th Avenue", "101 0101"); Listing l11 = new Listing("Zeek", "12th Avenue", "121 2121"); // insert and fetch nodes t.insert(l9); t.insert(l7); t.insert(l10); t.insert(l2); t.insert(l8); t.insert(l1); t.insert(l4); t.insert(l3); t.insert(l6); t.insert(l5); System.out.println(t.fetch("Carol")); System.out.println(t.fetch("Sally")); System.out.println(t.fetch("Ted")); // delete nodes t.delete("Carol"); // a node with NO children System.out.println(t.fetch("Carol")); t.delete("Sally"); // a node with ONE child System.out.println(t.fetch("Sally")); t.delete("Ted"); // a node with TWO children System.out.println(t.fetch("Ted")); // update nodes t.update("Bill", l3); System.out.println(t.fetch("Carol")); System.out.println(t.fetch("Bill")); System.exit(0); } } Exercise Lab 8:Sorting Merge Sort Class name: MergeSort Description: Merge Sort is based on the idea that two sorted sublists, A and B, can be merged into one sorted list, T, by comparing the minimum items in each sublist. The smaller of the two items is transferred to list T. This process is continued until either sublist A or sublist B is empty. Source: MergeSort.java public class MergeSort { public static void mergeSort(int items[], int temp[], int leftIndex, int rightIndex) { int midIndex, nItems; nItems = rightIndex - leftIndex + 1 ; if (nItems == 1) // base case return; midIndex = (rightIndex + leftIndex) / 2; mergeSort(items, temp, leftIndex, midIndex); // first reduced problem mergeSort(items, temp, midIndex+1, rightIndex); // second reduced problem merge(items, temp, leftIndex, midIndex+1, rightIndex); // general solution return; } // end of mergeSort method public static void merge(int items[], int temp[], int leftIndex, int midIndex, int rightIndex) { int leftEnd, nItems, tempsIndex; leftEnd = midIndex - 1; tempsIndex = leftIndex; nItems = rightIndex - leftIndex + 1; while ((leftIndex <= leftEnd) && (midIndex <= rightIndex)) // move items into temp { if (items[leftIndex] <= items[midIndex]) // move item from left sublist { temp[tempsIndex] = items[leftIndex]; tempsIndex = tempsIndex + 1; leftIndex = leftIndex +1; } else // move item from right sublist into temp { temp[tempsIndex] = items[midIndex]; tempsIndex = tempsIndex + 1; midIndex = midIndex + 1; } } if( leftIndex <= leftEnd) // left sublist is not empty { while (leftIndex <= leftEnd) // copy remainder of left sublist to temp { temp[tempsIndex] = items[leftIndex]; leftIndex = leftIndex + 1; tempsIndex = tempsIndex + 1; } } else // right sublist is not empty { temp while (midIndex <= rightIndex) // copy reminder of right sublist into { temp[tempsIndex] = items[midIndex]; midIndex = midIndex + 1; tempsIndex = tempsIndex + 1; } } for (int i=0; i < nItems; i++) // copy temp into items { items[rightIndex] = temp[rightIndex]; rightIndex = rightIndex - 1; } }// end merge method }// end of class Quick Sort Class name: QuickSort Description: the item in the middle of the unsorted array is chosen to be a pivot value. By the end of the pass the item is positioned into its proper sorted place in the array, partitioning it into two parts. In addition, the other items in the array have been positioned such that the value of the items to the left of the pivot value are all less than it, and the values to the right of the pivot are all greater than it. Source: QuickSort.java public class QuickSort { public static void quickSort(int [] items, int leftIndex, int rightIndex) { int i, j, temp, pivotValue, partitionSize; partitionSize = rightIndex - leftIndex +1; if(partitionSize <= 1) // base case, one item to be sorted return; pivotValue = items[(leftIndex + rightIndex) / 2]; i = leftIndex; // initialize the two partition indices j = rightIndex; do { while (items[i] < pivotValue) // left partition item is in the correct partition i++; while (items[j] > pivotValue) // right partition item is in the correct partition j--; if (i<=j) // pointers have not crossed, switch items in wrong partition { temp = items[i]; items[i] = items[j]; items[j]=temp; i++; j--; } } while (i <= j); // the pointers have not crossed quickSort(items, leftIndex, j); //reduced problems: sort left partition, quickSort(items, i, rightIndex); // sort right partition }// end of quickSort } Application Program Class name: MainSortingAlgorithms Description: Sort 10 data time using both MergeSort and QuickSort Source: MainSortingAlgorithms.java public class MainSortingAlgorithms { public static void main(String args[]) { int[] items1 = {6, 2, 3, 1, 7, 5, 8, 9, 10, 4}; int[] items2 = {6, 2, 3, 1, 7, 5, 8, 9, 10, 4}; int[] temp = new int[10]; MergeSort.mergeSort(items1, temp, 0, 9); System.out.println("Merge Sort results"); for(int i=0; i<10; i++) System.out.print(items1[i] + " "); QuickSort.quickSort(items2, 0, 9); System.out.println("\n\nQuick Sort results"); for(int i=0; i<10; i++) System.out.print(items2[i] + " "); } } Exercise Lab 9: Graph Simple Directed Graph Class name: SimpleGraph Description: Fully encapsulated data structure whose vertices sotre objects in a class named Listing Source: SimpleGraph.java public class SimpleGraph // a directed graph { Listing vertex[ ]; //the reference to the vertex array int edge[ ][ ]; // reference to the adjacency matrix array int max, numberOfVertices; public SimpleGraph(int n) { vertex = new Listing[n]; // allocation of the vertex array edge = new int[n][n]; // adjacency matrix with all elements set to 0 max = n; numberOfVertices = 0; } public boolean insertVertex(int vertexNumber, Listing newListing) { if (vertexNumber >= max) //the graph is full return false; vertex[vertexNumber] = newListing.deepCopy(); numberOfVertices++; return true; } public boolean insertEdge(int fromVertex, int toVertex) { if(vertex[fromVertex] == null || vertex[toVertex] == null) // nonexistent vertex return false; edge[fromVertex][toVertex] = 1; return true; } public void showVertex(int vertexNumber) { System.out.println(vertex[vertexNumber]); } public void showEdges(int vertexNumber) //edges emanating from vertexNumber { for(int column=0; column<numberOfVertices; column++) { if(edge[vertexNumber][column] == 1) // there is an edge System.out.println(vertexNumber + "," + column); } } }// end of SimpleGraph class Node Structure Class name: Listing Description: the definition of the hub city objects stored in the vertices Source: Listing.java // definition of a hub city (a vertex) public class Listing { private String name; { } public Listing(String n) name=n; public String toString() { return("Name is " + name); } public Listing deepCopy() { Listing clone = new Listing(name); return clone; } } Airline Hub Application Program Class name: MainSimpleGraph Description: Airline Hub Application that uses a SimpleGraph object to store the Hub Cities Source: MainSimpleGraph.java public class MainSimpleGraph { public static void main(String[] args) { SimpleGraph flyUS = new SimpleGraph(5); Listing v0 = new Listing("Philadelphia"); Listing v1 = new Listing("New York"); Listing v2 = new Listing("Boston"); Listing v3 = new Listing("Los Angeles"); Listing v4 = new Listing("Huston"); // add the hub cities to the graph as vertices flyUS.insertVertex(0, v0); flyUS.insertVertex(1, v1); flyUS.insertVertex(2, v2); flyUS.insertVertex(3, v3); flyUS.insertVertex(4, v4); // add the routes to the graph as edges flyUS.insertEdge(0,1); flyUS.insertEdge(0,3); flyUS.insertEdge(1,2); flyUS.insertEdge(1,3); flyUS.insertEdge(2,1); flyUS.insertEdge(3,4); flyUS.insertEdge(4,0); flyUS.insertEdge(4,3); // output the hubs and the routes stored in the graph for(int i=0; i<5; i++) { System.out.print("hub " + i + "\'s "); flyUS.showVertex(i); System.out.println("its routes are: "); flyUS.showEdges(i); } //end the output loop } //end the method main } // end the application