Data Structures and Algorithms, Winter term 2018 Practice Assignment 3

Size: px
Start display at page:

Download "Data Structures and Algorithms, Winter term 2018 Practice Assignment 3"

Transcription

1 German University in Cairo Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Wael Abouelsaadat Data Structures and Algorithms, Winter term 2018 Practice Assignment 3 Exercise 3-1 Search in a Stack Write a method to find the position of a given element in a stack counting from the top of the stack. More precisely, the method should return 0 if the element occurs on the top, 1 if there is another element on top of it, and so on. If the element occurs several times, the topmost position should be returned. If the element doesn t occur at all, -1 must be returned. You are asked to write this method in two different ways; one way is to implement it internally inside the ArrayStack class and the other way is to implement it externally in a separate class. Important: At the end the stack should be returned to the original state (i.e. no elements should be removed and the order of the elements should not change). a) Internal method public class ArrayStack private int[] thestack; private int maxsize; private int top; public ArrayStack(int s) maxsize = s; thestack = new int[maxsize]; top = -1; public void push(int elem) top++; thestack[top] = elem; public int pop() int result = thestack[top]; top--; return result; public int top() return thestack[top]; public boolean isfull() return (top == (maxsize-1) ); public boolean isempty() 1

2 return (top == -1); public int size() return (top+1); public void printstack() if(top == -1) System.out.println("Stack is empty!!\n"); else System.out.println(theStack[top]+" <- top"); for(int i=top-1; i>=0; i--) System.out.println(theStack[i]); System.out.println(); //Exercise 3-1, internal implementation public int search(int target) for (int i = top; i >= 0 ; i--) if(thestack[i] == target) return top -i; return -1; b) External method public class StackSearching //Exercise 3-1, external implementation public static int searchfor(arraystack s1,int target) int position = 0; boolean found = false; //will be used to return s1 to its original state ArrayStack s2 = new ArrayStack(s1.size()); //search while (!(s1.isempty())) if(s1.top() == target) found = true; break; s2.push(s1.pop()); position ++; //return s1 to its original state while((!(s2.isempty())) && (!(s1.isfull())) ) s1.push(s2.pop()); if(!found) position = -1; return position; public static void main(string[] args) ArrayStack s = new ArrayStack(10); s.push(4); 2

3 s.push(20); s.push(7); s.push(1); System.out.println(12+": internally "+ s.search(12)+", externally: "+ searchfor(s, 12)); System.out.println(1+": internally "+ s.search(1)+", externally: "+ searchfor(s, 1)); System.out.println(20+": internally "+ s.search(20)+", externally: "+ searchfor(s, 20)); Exercise 3-2 Stack Decompose You are required to implement a method public static ArrayStack decompose(arraystack x) where x is a stack of ints. The method is required to decompose the values stored in the stack x into two groups: values in the odd positions remain in the stack x values in the even positions should be stored in a new stack, say y The method should finally return the newly created stack y containing the values in the even positions. We will assume that the value on top of the stack is in position 1. Make sure that the order of elements in both stacks will remain the same as the order of elements in the initial stack. The following is a sample method run: Input: x Effect of method: x y Only stacks can be used!. Implement the method decompose externally, i.e. using the methods available in the stack class. public class StackDecompose public static ArrayStack decompose(arraystack x) ArrayStack y = new ArrayStack(x.size()/2); ArrayStack odd = new ArrayStack(x.size()/2+1); ArrayStack even = new ArrayStack(x.size()/2); while(!x.isempty()) odd.push(x.pop()); if(!x.isempty()) even.push(x.pop()); while(!odd.isempty()) 3

4 x.push(odd.pop()); while(!even.isempty()) y.push(even.pop()); return y; //alternative solution public static ArrayStack decompose2(arraystack x) ArrayStack reverse = new ArrayStack(x.size()); ArrayStack y = new ArrayStack(x.size()/2); boolean isoddsized = x.size()%2 == 1; while(!x.isempty()) reverse.push(x.pop()); while(!reverse.isempty()) if(isoddsized) x.push(reverse.pop()); if(!reverse.isempty()) y.push(reverse.pop()); else y.push(reverse.pop()); x.push(reverse.pop()); return y; public static void main(string[] args) ArrayStack s = new ArrayStack(8); s.push(6); s.push(9); s.push(5); s.push(4); s.push(1); s.push(2); s.push(7); ArrayStack y = decompose2(s); y.printstack(); Exercise 3-3 To be discussed in the Tutorial Stack Sorting Write an external method to sort a stack by putting the smaller elements towards the bottom. public class StackSort public static void stacksort(arraystack s1) int count = s1.size(); ArrayStack s2 = new ArrayStack(count); int tmp; while (count>0) int min = s1.pop(); for (int i =1; i<count; i++) 4

5 tmp = s1.pop(); if (tmp<min) s2.push(min); min = tmp; else s2.push (tmp); s1.push(min); while(!s2.isempty()) s1.push(s2.pop()); count--; public static void main(string[] args) ArrayStack s = new ArrayStack(8); s.push(6); s.push(9); s.push(5); s.push(4); s.push(1); s.push(2); s.push(7); stacksort(s); Exercise 3-4 Cube Game For this problem you are going to implement a method for a simple game. In this game you are given a stack of cubes which can only be accessed from the top. You are required to determine whether the sum of the elements in the top half of the stack is equal to the sum of the elements in the bottom half. If the number of elements is odd, ignore the middle element. You have to end your check with the contents of the stack being in the same order as they were given to you. For the purpose of this problem implement the method static boolean check(arraystack x), which performs the check operation described above over a stack x of integers and returns true if both halves are equal and false otherwise. Note: you are not allowed to use any data structure except stacks for solving this problem. Sample run: Input: Output: true, with = = 12 Input: Output: false, with

6 public class CubeGame public static boolean check(arraystack s) int size = s.size(); int sum1=0; int sum2=0; int x; ArrayStack temp=new ArrayStack(size); // popping the first half for(int i = 0; i < size / 2; i++) x = s.pop(); sum1 += x; temp.push(x); // in the case of an odd-sized stack if(size % 2 == 1) temp.push(s.pop()); // popping the second half for(int i = 0; i < size / 2; i++) x = s.pop(); sum2 += x; temp.push(x); // returning back the elements while(!temp.isempty()) s.push(temp.pop()); return sum1 == sum2; public static void main(string args[]) ArrayStack s = new ArrayStack(5); s.push(9); s.push(8); s.push(8); s.push(4); System.out.println(check(s)); Exercise 3-5 Reverse a Stack For this exercise, you are required to reverse the contents of a Stack. Use the ArrayStack implementation posted on the website. a) First do it internally, i.e. as an instance method inside the ArrayStack class Add this instance method to the ArrayStack class: public void reverse() for(int i=0; i<(top+1)/2; i++) int temp = thestack[i]; thestack[i] = thestack[top-i]; thestack[top-i] = temp; 6

7 b) Then do it externally, you should implement 3 external methods: 1. Write a method static ArrayStack reverse1(arraystack s) that takes a stack as a parameter and returns its reverse, you are allowed to destruct the original stack. 2. Write a method static ArrayStack reverse2(arraystack s) that takes a stack as a parameter and returns its reverse, but this time at the end the stack should be returned to the original state. 3. Write a method static void reverse3(arraystack s) that takes a stack as a parameter and reverses it and puts the reversed stack in the original. You should display the stack elements before and after calling each method. public class ReverseStack public static ArrayStack reverse1(arraystack s) ArrayStack result = new ArrayStack(s.size()); while(!s.isempty()) result.push(s.pop()); return result; public static ArrayStack reverse2(arraystack s) ArrayStack result = new ArrayStack(s.size()); ArrayStack tmp = new ArrayStack(s.size()); while(!s.isempty()) tmp.push(s.top()); result.push(s.pop()); while(!tmp.isempty()) s.push(tmp.pop()); return result; public static void reverse3(arraystack s) ArrayStack s1=new ArrayStack(s.size()); ArrayStack s2=new ArrayStack(s.size()); while(!s.isempty()) s1.push(s.pop()); while(!s1.isempty()) s2.push(s1.pop()); while(!s2.isempty()) s.push(s2.pop()); public static void main(string[] args) ArrayStack s = new ArrayStack(5); s.push(5); s.push(44); System.out.println("Original Stack before reverse:"); ArrayStack r = reverse1(s); System.out.println("Original Stack after reverse:"); System.out.println("Reverse Stack:"); 7

8 r.printstack(); s.push(5); s.push(44); System.out.println("Original Stack before reverse:"); r = reverse2(s); System.out.println("Original Stack after reverse:"); System.out.println("Reverse Stack:"); r.printstack(); System.out.println("Original Stack before reverse:"); reverse3(s); System.out.println("Original Stack after reverse:"); 8

9 Exercise 3-6 Remove n th Element You are given a stack with the methods pop, push, top, isempty, isfull and size. You are required to implement a method static void removenth(arraystack s, int n) which removes the n th element from the bottom of the stack s. Assume that the value of n will be between 1 and size of the given stack, inclusive. For instance, the call removenth(s, 1) should remove the lowermost item of the stack s. The stack s should be unchanged except for the deleted element. You may only use stacks to solve this problem. Do not re-implement the stack operations. public class RemovingNthStack public static void removenth(arraystack s, int n) int size = s.size(); ArrayStack temp = new ArrayStack(size); for(int i=0; i<size-n; i++) temp.push(s.pop()); if(!s.isempty()) s.pop(); while(!temp.isempty()) s.push(temp.pop()); public static void main(string[] args) ArrayStack s= new ArrayStack(5); s.push(1); s.push(5); s.push(23); s.push(8); s.push(2); removenth(s, 3); Exercise 3-7 Midterm Exam 2015 Suppose we have a stack of integers. Initially the integers are not sorted. We would like to rearrange the stack using the insertion sort algorithm presented in lectures for arrays. The elements should be in ascending order where the smallest element will be on top of the stack and the largest at the bottom of the stack. a) Write an external Java method void stacksort(objectstack s) that takes a stack of integers s and sorts the stack based on the insertion sort algorithm for arrays. Please note that you are not allowed to use except stacks and the following constructor and methods: public ObjectStack(int maxsize) public void push(object o) public Object pop() public Object top() public boolean isempty() public boolean isfull() public int size() public class Ex2 public static void stacksort1(stackobj s) // create two new empty stacks 9

10 StackObj x = new StackObj(s.size()); StackObj y = new StackObj(s.size()); // loop on all unsorted elements while (!s.isempty()) int tmp = (Integer) s.pop(); // the first element if (x.isempty()) x.push(tmp); else while (!x.isempty()&&(integer)x.top()>tmp) y.push(x.pop()); x.push(tmp); // return elements to their position while (!y.isempty()) x.push(y.pop()); // put the sorted elements in stack (s) again while (!x.isempty()) s.push(x.pop()); /* Another solution */ public static void stacksort2(stackobj s) // create two new empty stacks StackObj x = new StackObj(s.size() - 1); StackObj y = new StackObj(s.size() - 1); while (s.size() > 1) // move all elements except the first element x.push(s.pop()); // loop on all moved elements while (!x.isempty()) // the element is in its correct position if ((Integer) s.top() > (Integer) x.top()) s.push(x.pop()); else while(!s.isempty()&& (Integer)s.top()<(Integer)x.top()) y.push(s.pop()); s.push(x.pop()); // return elements to their position while (!y.isempty()) s.push(y.pop()); public static void main(string[] args) StackObj s = new StackObj(4); s.push(1); s.push(4); s.push(2); stacksort1(s); b) Given an initially unordered stack 10

11 1. What is the best case complexity of the algorithm? Justify your answer. 4cm Best Case O(n), because there will be only one element out of place, therefore the loop will execute n times and the inner loop will be executed only once. 2. What is the worst case complexity of the algorithm? Justify your answer. 4cm Worst Case O(n 2 ), because all elements will be out of place and both nested loops will be executed n times 3. What is the invariant of the algorithm? Justify your answer. The invariant: After n passes, n elements are partially sorted. because in each iteration we insert one of the unsorted elements in its correct position. 11

Data Structures and Algorithms Winter term 2012

Data Structures and Algorithms Winter term 2012 Page 0 German University in Cairo November 4, 2012 Faculty of Media Engineering and Technology Prof. Dr. Slim Abdennadher Data Structures and Algorithms Winter term 2012 Midterm Exam Bar Code Instructions:

More information

Data Structures and Algorithms Winter Semester

Data Structures and Algorithms Winter Semester Page 0 German University in Cairo October 24, 2018 Media Engineering and Technology Faculty Prof. Dr. Slim Abdennadher Dr. Wael Abouelsadaat Data Structures and Algorithms Winter Semester 2018-2019 Midterm

More information

Data Structures and Algorithms, Winter term 2017 Practice Assignment 7

Data Structures and Algorithms, Winter term 2017 Practice Assignment 7 German University in Cairo Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Wael Abouelsaadat Data Structures and Algorithms, Winter term 2017 Practice Assignment 7 Exercise 7-1 Using the

More information

ECE 242 Fall 13 Exam I Profs. Wolf and Tessier

ECE 242 Fall 13 Exam I Profs. Wolf and Tessier ECE 242 Fall 13 Exam I Profs. Wolf and Tessier Name: ID Number: Maximum Achieved Question 1 16 Question 2 24 Question 3 18 Question 4 18 Question 5 24 Total 100 This exam is closed book, closed notes.

More information

CIS Fall Data Structures Midterm exam 10/16/2012

CIS Fall Data Structures Midterm exam 10/16/2012 CIS 2168 2012 Fall Data Structures Midterm exam 10/16/2012 Name: Problem 1 (30 points) 1. Suppose we have an array implementation of the stack class, with ten items in the stack stored at data[0] through

More information

Complexity, General. Standard approach: count the number of primitive operations executed.

Complexity, General. Standard approach: count the number of primitive operations executed. Complexity, General Allmänt Find a function T(n), which behaves as the time it takes to execute the program for input of size n. Standard approach: count the number of primitive operations executed. Standard

More information

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 CMPSCI 187: Programming With Data Structures Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 Implementing Stacks With Arrays The Idea of the Implementation Data Fields

More information

Topic 6: Inner Classes

Topic 6: Inner Classes Topic 6: Inner Classes What's an inner class? A class defined inside another class Three kinds: inner classes static nested classes anonymous classes this lecture: Java mechanisms later: motivation & typical

More information

1. Stack Implementation Using 1D Array

1. Stack Implementation Using 1D Array Lecture 5 Stacks 1 Lecture Content 1. Stack Implementation Using 1D Array 2. Stack Implementation Using Singly Linked List 3. Applications of Stack 3.1 Infix and Postfix Arithmetic Expressions 3.2 Evaluate

More information

CSCD 326 Data Structures I Stacks

CSCD 326 Data Structures I Stacks CSCD 326 Data Structures I Stacks 1 Stack Interface public interface StackInterface { public boolean isempty(); // Determines whether the stack is empty. // Precondition: None. // Postcondition: Returns

More information

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed stack method of expression evaluation in 1955. Topic 15 Implementing and Using "stack n. The set of things a person has to do in the future. "I haven't done it yet because every time I pop my stack something new gets pushed." If you are interrupted

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Stacks Eng. Anis Nazer First Semester 2017-2018 Stack An Abstract data type (ADT) Accessed only on one end Similar to a stack of dishes you can add/remove on top of stack

More information

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack. STACK Stack ADT 2 A stack is an abstract data type based on the list data model All operations are performed at one end of the list called the top of the stack (TOS) LIFO (for last-in first-out) list is

More information

Midterm Exam 2 CS 455, Spring 2011

Midterm Exam 2 CS 455, Spring 2011 Name: USC loginid (e.g., ttrojan): Midterm Exam 2 CS 455, Spring 2011 March 31, 2011 There are 6 problems on the exam, with 50 points total available. There are 7 pages to the exam, including this one;

More information

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004) COMP250: Stacks Jérôme Waldispühl School of Computer Science McGill University Based on slides from (Goodrich & Tamassia, 2004) 2004 Goodrich, Tamassia The Stack ADT A Stack ADT is a list that allows only

More information

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011 Stacks (5.1) CSE 2011 Winter 2011 26 January 2011 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error

More information

CSEN 301 Data Structures and Algorithms

CSEN 301 Data Structures and Algorithms CSEN 301 Data Structures and Algorithms Lecture 5: Queues: Implementation and usage Prof. Dr. Slim Abdennadher slim.abdennadher@guc.edu.eg German University Cairo, Department of Media Engineering and Technology

More information

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures 1.00 Lecture 26 Data Structures: Introduction Stacks Reading for next time: Big Java: 19.1-19.3 Data Structures Set of primitives used in algorithms, simulations, operating systems, applications to: Store

More information

Searching and Sorting (Savitch, Chapter 7.4)

Searching and Sorting (Savitch, Chapter 7.4) Searching and Sorting (Savitch, Chapter 7.4) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort What is an algorithm? A finite set of precise instruc6ons for performing

More information

CMPS 390 Data Structures

CMPS 390 Data Structures CMPS 390 Data Structures Programming Assignment #02 Infix to Postfix 1. Complete two methods in Java program (Postfix.java) to convert an infix expression into a postfix expression and evaluate the postfix

More information

What is an algorithm?

What is an algorithm? /0/ What is an algorithm? Searching and Sorting (Savitch, Chapter 7.) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort A finite set of precise instrucons for performing

More information

Interfaces & Generics

Interfaces & Generics Interfaces & Generics CSC207 Winter 2018 The Programming Interface The "user" for almost all code is a programmer. That user wants to know:... what kinds of object your class represents... what actions

More information

CS 455 Midterm 2 Fall 2017 [Bono] Nov. 7, 2017

CS 455 Midterm 2 Fall 2017 [Bono] Nov. 7, 2017 Name: USC NetID (e.g., ttrojan): CS 455 Midterm 2 Fall 2017 [Bono] Nov. 7, 2017 There are 6 problems on the exam, with 62 points total available. There are 10 pages to the exam (5 pages double-sided),

More information

Computer Science 1 Ah

Computer Science 1 Ah UNIVERSITY OF EDINBURGH course CS0077 COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS Computer Science 1 Ah Resit Examination Specimen Solutions Date: Monday 1st September 2003 Time: 09:30 11:00

More information

CT 229 Object-Oriented Programming Continued

CT 229 Object-Oriented Programming Continued CT 229 Object-Oriented Programming Continued 24/11/2006 CT229 Summary - Inheritance Inheritance is the ability of a class to use the attributes and methods of another class while adding its own functionality

More information

MIDTERM WEEK - 9. Question 1 : Implement a MyQueue class which implements a queue using two stacks.

MIDTERM WEEK - 9. Question 1 : Implement a MyQueue class which implements a queue using two stacks. Ashish Jamuda Week 9 CS 331-DATA STRUCTURES & ALGORITHMS MIDTERM WEEK - 9 Question 1 : Implement a MyQueue class which implements a queue using two stacks. Solution: Since the major difference between

More information

Write a program to implement stack or any other data structure in Java ASSIGNMENT NO 15

Write a program to implement stack or any other data structure in Java ASSIGNMENT NO 15 Write a program to implement stack or any other data structure in Java ASSIGNMENT NO 15 Title: Demonstrate implementation of data structure in Java Objectives: To learn implementation of data structure

More information

Heaps. Heaps. A heap is a complete binary tree.

Heaps. Heaps. A heap is a complete binary tree. A heap is a complete binary tree. 1 A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. A min-heap is defined

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

Chapter 2. Stack & Queues. M hiwa ahmad aziz

Chapter 2. Stack & Queues.   M hiwa ahmad aziz . Chapter 2 Stack & Queues www.raparinweb.com M hiwa ahmad aziz 1 Stack A stack structure with a series of data elements that Allows access to only the last item inserted. An item is inserted or removed

More information

C Sc 227 Practice Test 2 Section Leader Your Name 100pts. a. 1D array b. PriorityList<E> c. ArrayPriorityList<E>

C Sc 227 Practice Test 2 Section Leader Your Name 100pts. a. 1D array b. PriorityList<E> c. ArrayPriorityList<E> C Sc 227 Practice Test 2 Section Leader Your Name 100pts 1. Approximately how many lectures remain in C Sc 227 (give or take 2)? (2pts) 2. Determine the tightest upper bound runtimes of the following loops.

More information

CSIS 10B Lab 2 Bags and Stacks

CSIS 10B Lab 2 Bags and Stacks CSIS 10B Lab 2 Bags and Stacks Part A Bags and Inheritance In this part of the lab we will be exploring the use of the Bag ADT to manage quantities of data of a certain generic type (listed as T in the

More information

Data Structures and Algorithms, Winter term 2017 Practice Assignment 10

Data Structures and Algorithms, Winter term 2017 Practice Assignment 10 German University in Cairo Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Wael Abouelsaadat Data Structures and Algorithms, Winter term 2017 Practice Assignment 10 Exercise 10-1 Traversal

More information

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial: Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Factorial (1) Recall the formal definition of calculating the n factorial: 1 if n = 0 n! = n (n 1) (n 2) 3 2

More information

COS 226 Algorithms and Data Structures Spring Midterm Exam

COS 226 Algorithms and Data Structures Spring Midterm Exam COS 226 Algorithms and Data Structures Spring 2016 Midterm Exam This midterm has 7 questions for a total of 66 points. You have 80 minutes. The exam is closed book, and no calculators or other electronic

More information

Associate Professor Dr. Raed Ibraheem Hamed

Associate Professor Dr. Raed Ibraheem Hamed Associate Professor Dr. Raed Ibraheem Hamed University of Human Development, College of Science and Technology Computer Science Department 2015 2016 1 What this Lecture is about: Stack Structure Stack

More information

Data Structures G5029

Data Structures G5029 Data Structures G5029 Lecture 2 Kingsley Sage Room 5C16, Pevensey III khs20@sussex.ac.uk University of Sussex 2006 Lecture 2 Stacks The usual analogy is the stack of plates. A way of buffering a stream

More information

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam Page 0 German University in Cairo April 6, 2017 Media Engineering and Technology Faculty Prof. Dr. Slim Abdennadher CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam Bar Code

More information

Data Structures and Algorithms Winter term 2006/2007 Final Exam

Data Structures and Algorithms Winter term 2006/2007 Final Exam Page 0 German University in Cairo Winter 2006/2007 Computer Science Department Prof. Dr. Slim Abdennadher Data Structures and Algorithms Winter term 2006/2007 Final Exam Bar Code Instructions: Read carefully

More information

CSE 143 SAMPLE MIDTERM

CSE 143 SAMPLE MIDTERM CSE 143 SAMPLE MIDTERM 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust code

More information

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

CS171 Midterm Exam. October 29, Name:

CS171 Midterm Exam. October 29, Name: CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and

More information

LECTURE 17. Array Searching and Sorting

LECTURE 17. Array Searching and Sorting LECTURE 17 Array Searching and Sorting ARRAY SEARCHING AND SORTING Today we ll be covering some of the more common ways for searching through an array to find an item, as well as some common ways to sort

More information

Data Structures and Algorithms Winter term 2016

Data Structures and Algorithms Winter term 2016 Page 0 German University in Cairo December 26, 2016 Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Wael Abouelsaadat Data Structures and Algorithms Winter term 2016 Final Exam Bar Code

More information

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return 0. How would we write the BinaryHeap siftdown function recursively? [0] 6 [1] [] 15 10 Name: template class BinaryHeap { private: int maxsize; int numitems; T * heap;... [3] [4] [5] [6] 114 0

More information

Ashish Jamuda CS 331 DATA STRUCTURES & ALGORITHMS COURSE FINAL EXAM

Ashish Jamuda CS 331 DATA STRUCTURES & ALGORITHMS COURSE FINAL EXAM Ashish Jamuda CS 331 DATA STRUCTURES & ALGORITHMS COURSE FINAL EXAM Question 1: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. This problem can be solved

More information

/** * finds the index of v in a if present * * * * */ public static int findinsortedarray(int[] a, int v) {...

/** * finds the index of v in a if present * * * * */ public static int findinsortedarray(int[] a, int v) {... 1 2 /** * finds the index of v in a if present * * @pre??? * * @post??? * * */ public static int findinsortedarray(int[] a, int v) {... } 3 /** * finds the index of v in a if present * * @pre a[i] < a[i+1]

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) 1 Short Answer (10 Points Each) 1. For the following one-dimensional array, show the final array state after each pass of the three sorting algorithms. That is, after each iteration of the outside loop

More information

McGill University Faculty of Science School of Computer Science. MIDTERM EXAMINATION - Sample solutions. COMP-250: Introduction to Computer Science

McGill University Faculty of Science School of Computer Science. MIDTERM EXAMINATION - Sample solutions. COMP-250: Introduction to Computer Science STUDENT NAME: STUDENT ID: McGill University Faculty of Science School of Computer Science MIDTERM EXAMINATION - Sample solutions COMP-250: Introduction to Computer Science March 12, 2014 Examiner: Prof.

More information

No Aids Allowed. Do not turn this page until you have received the signal to start.

No Aids Allowed. Do not turn this page until you have received the signal to start. CSC 148H Midterm Fall 2007 St. George Campus Duration 50 minutes Student Number: Family Name: Given Name: No Aids Allowed. Do not turn this page until you have received the signal to start. # 1: /10 #

More information

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1 CSE 1 Complexity Analysis Program Efficiency [Sections 12.1-12., 12., 12.9] Count number of instructions executed by program on inputs of a given size Express run time as a function of the input size Assume

More information

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle. Stacks 1 Stacks The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle. 2 Main stack operations Insertion and removal are defined by: push(e): inserts

More information

CSEN 202: Introduction to Computer Programming Spring term Final Exam

CSEN 202: Introduction to Computer Programming Spring term Final Exam Page 0 German University in Cairo May 28, 2016 Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Wael Aboul Saadat CSEN 202: Introduction to Computer Programming Spring term 2015-2016 Final

More information

Introduction to Programming (CS112): Sample

Introduction to Programming (CS112): Sample Introduction to Programming (CS112): Sample Name: Netid: ffl Write your answers directly on the examination paper, including any work that you wish to be considered for partial credit. Use the back side

More information

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

Recursion. Tracing Method Calls via a Stack. Beyond this lecture... Recursion EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004 1.00/1.001 Introduction to Computers and Engineering Problem Solving Final / December 13, 2004 Name: Email Address: TA: Solution Section: You have 180 minutes to complete this exam. For coding questions,

More information

CSCE 2014 Final Exam Spring Version A

CSCE 2014 Final Exam Spring Version A CSCE 2014 Final Exam Spring 2017 Version A Student Name: Student UAID: Instructions: This is a two-hour exam. Students are allowed one 8.5 by 11 page of study notes. Calculators, cell phones and computers

More information

C/C++ Programming Lecture 18 Name:

C/C++ Programming Lecture 18 Name: . The following is the textbook's code for a linear search on an unsorted array. //***************************************************************** // The searchlist function performs a linear search

More information

CS101 Part 2: Practice Questions Algorithms on Arrays, Classes and Objects, String Class, Stack Class

CS101 Part 2: Practice Questions Algorithms on Arrays, Classes and Objects, String Class, Stack Class CS1 Part 2: Algorithms on Arrays, Classes and Objects, String Class, Stack Class 1. Write a method that, given two sorted arrays of integers, merges the two arrays into a single sorted array that is returned.

More information

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write

More information

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES Midterm Examination Douglas Wilhelm Harder 1.5 hrs, 2005/02/17 11 pages Name (last, first):

More information

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011 CMPSCI 187: Programming With Data Structures Lecture 12: Implementing Stacks With Linked Lists 5 October 2011 Implementing Stacks With Linked Lists Overview: The LinkedStack Class from L&C The Fields and

More information

Outline and Reading. The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1.

Outline and Reading. The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1. Stacks Outline and Reading The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1.5) Stacks 2 Abstract Data Types (ADTs) An abstract data

More information

Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

More information

CMPSCI 187: Programming With Data Structures. Review for First Midterm 9 October 2011

CMPSCI 187: Programming With Data Structures. Review for First Midterm 9 October 2011 CMPSCI 187: Programming With Data Structures Review for First Midterm 9 October 2011 Format Two hours, closed-book, no calculators, computers, etc. Question types as on practice exam: Java Concepts (10

More information

Introduction to Computer Programming, Spring Term 2018 Practice Assignment 9 Discussion:

Introduction to Computer Programming, Spring Term 2018 Practice Assignment 9 Discussion: German University in Cairo Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Mohammed Abdel Megeed Introduction to Computer Programming, Spring Term 2018 Practice Assignment 9 Discussion:

More information

CS 112 Practice Midterm Solutions

CS 112 Practice Midterm Solutions Question 1) CS 112 Practice Midterm Solutions class TreeNode void set_left (TreeNode new_left); // Update lchild to point to new_left void set_data (T new_data); // Set the data field to new_data

More information

Practice test for Midterm 1; solutions

Practice test for Midterm 1; solutions Practice test for Midterm 1; solutions November 1, 2 1 1 C++ review & UML diagrams Write a function which takes a vector of int and returns true if all the elements of the vector are positive ( 0) and

More information

Name CPTR246 Spring '17 (100 total points) Exam 3

Name CPTR246 Spring '17 (100 total points) Exam 3 Name CPTR246 Spring '17 (100 total points) Exam 3 1. Linked Lists Consider the following linked list of integers (sorted from lowest to highest) and the changes described. Make the necessary changes in

More information

CS 455 MT 2 Sample Questions

CS 455 MT 2 Sample Questions CS 455 MT 2 Sample Questions [CS455 Bono] This doesn t cover everything. There s likely to be at least one question about exceptions (e.g., writing some code with exceptions, or saying what some code does

More information

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science IT 4043 Data Structures and Algorithms Budditha Hettige Department of Computer Science 1 Syllabus Introduction to DSA Abstract Data Types List Operation Using Arrays Stacks Queues Recursion Link List Sorting

More information

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016 Name: USC NetID (e.g., ttrojan): CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016 There are 5 problems on the exam, with 56 points total available. There are 10 pages to the exam (5 pages

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Introduction to Computer Science II (ITI 1121) Midterm Examination

Introduction to Computer Science II (ITI 1121) Midterm Examination Introduction to Computer Science II (ITI 1121) Midterm Examination Instructor: Marcel Turcotte February 2007, duration: 2 hours Identification Student name: Student number: Signature: Instructions 1. 2.

More information

Searching & Sorting in Java Bubble Sort

Searching & Sorting in Java Bubble Sort With the bubble sort, the basic idea is to compare adjacent values and exchange them if they are not in order. Consider the following example which shows the first pass through the algorithm. 1. Compare

More information

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows: STACKS A stack is a linear data structure for collection of items, with the restriction that items can be added one at a time and can only be removed in the reverse order in which they were added. The

More information

CS126 Final Exam Review

CS126 Final Exam Review CS126 Final Exam Review Fall 2007 1 Asymptotic Analysis (Big-O) Definition. f(n) is O(g(n)) if there exists constants c, n 0 > 0 such that f(n) c g(n) n n 0 We have not formed any theorems dealing with

More information

COS 226 Midterm Exam, Spring 2009

COS 226 Midterm Exam, Spring 2009 NAME: login ID: precept: COS 226 Midterm Exam, Spring 2009 This test is 10 questions, weighted as indicated. The exam is closed book, except that you are allowed to use a one page cheatsheet. No calculators

More information

CMPSCI 187: Programming With Data Structures. Review for Final Exam David Mix Barrington 10 December 2012

CMPSCI 187: Programming With Data Structures. Review for Final Exam David Mix Barrington 10 December 2012 CMPSCI 187: Programming With Data Structures Review for Final Exam David Mix Barrington 10 December 2012 Exam Overview Thursday 13 December, 1:30-3:30 p.m., Marcus 131 Format is the same as the Fall 2011

More information

Stack Implementation

Stack Implementation Stack Implementation (In Java Using BlueJ) What is BlueJ? BlueJ is a Java integrated development environment (IDE) which has been designed specifically for learning object oriented programming in Java.

More information

1. Introduction. Lecture Content

1. Introduction. Lecture Content Lecture 6 Queues 1 Lecture Content 1. Introduction 2. Queue Implementation Using Array 3. Queue Implementation Using Singly Linked List 4. Priority Queue 5. Applications of Queue 2 1. Introduction A queue

More information

Basic Data Structures

Basic Data Structures Basic Data Structures Some Java Preliminaries Generics (aka parametrized types) is a Java mechanism that enables the implementation of collection ADTs that can store any type of data Stack s1

More information

Data Abstraction and Specification of ADTs

Data Abstraction and Specification of ADTs CITS2200 Data Structures and Algorithms Topic 4 Data Abstraction and Specification of ADTs Example The Reversal Problem and a non-adt solution Data abstraction Specifying ADTs Interfaces javadoc documentation

More information

I. True/False: (2 points each)

I. True/False: (2 points each) CS 102 - Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2009 What is your name?: There are three sections: I. True/False..............50 points; (25 questions, 2 points each) II. Multiple

More information

I. True/False: (2 points each) On your bubble form fill out a for true and b for false.

I. True/False: (2 points each) On your bubble form fill out a for true and b for false. CS 102/107 - Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2010 What is your name?: There are three sections: I. True/False..............60 points; (30 questions, 2 points each) II. Multiple

More information

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.

More information

Basic Data Structures 1 / 24

Basic Data Structures 1 / 24 Basic Data Structures 1 / 24 Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24 Some Java Preliminaries Generics (aka parametrized types) is

More information

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003 1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 7, 2003 Name: Email Address: TA: Section: You have 90 minutes to complete this exam. For coding questions, you do not need to

More information

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below. C212 Early Evaluation Exam Mon Feb 10 2014 Name: Please provide brief (common sense) justifications with your answers below. 1. What is the type (and value) of this expression: 5 * (7 + 4 / 2) 2. What

More information

I. True/False: (2 points each)

I. True/False: (2 points each) CS 102 - Introduction to Programming Midterm Exam #2 - Prof. Reed Spring 2008 What is your name?: (2 points) There are three sections: I. True/False..............54 points; (27 questions, 2 points each)

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Abstract Data Type Stack Version of February 2, 2013 Abstract These lecture notes are meant

More information

ECE 242 Data Structures and Algorithms. Linked List I. Lecture 10. Prof.

ECE 242 Data Structures and Algorithms.  Linked List I. Lecture 10. Prof. ECE 242 Data Structures and Algorithms http://www.ecs.umass.edu/~polizzi/teaching/ece242/ Linked List I Lecture 10 Prof. Eric Polizzi Logistics ECE242 Recommendations The goal of projects is to help you

More information

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method

More information

C Sc 227 Practice Test 2 Section Leader Name 134pts ANSWERS

C Sc 227 Practice Test 2 Section Leader Name 134pts ANSWERS C Sc 227 Practice Test 2 Section Leader Name 134pts ANSWERS 1. Determine the tightest upper bound runtimes of the following loops. Express your answer in the Big-O notation we have been using in class

More information

Searching for Information. A Simple Method for Searching. Simple Searching. Class #21: Searching/Sorting I

Searching for Information. A Simple Method for Searching. Simple Searching. Class #21: Searching/Sorting I Class #21: Searching/Sorting I Software Design II (CS 220): M. Allen, 26 Feb. 18 Searching for Information Many applications involve finding pieces of information Finding a book in a library or store catalogue

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Abstract Data Type Stack Version of February 2, 2013 Abstract These lecture notes are meant

More information

CSE 214 Computer Science II Heaps and Priority Queues

CSE 214 Computer Science II Heaps and Priority Queues CSE 214 Computer Science II Heaps and Priority Queues Spring 2018 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Introduction

More information

CSE 143 SAMPLE MIDTERM SOLUTION

CSE 143 SAMPLE MIDTERM SOLUTION CSE 143 SAMPLE MIDTERM SOLUTION 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust

More information

Stacks Goodrich, Tamassia

Stacks Goodrich, Tamassia Stacks Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error conditions associated with operations Example:

More information

C22a: Problem Solving using Recursion

C22a: Problem Solving using Recursion CISC 3115 TY3 C22a: Problem Solving using Recursion Hui Chen Department of Computer & Information Science CUNY Brooklyn College 11/6/2018 CUNY Brooklyn College 1 Outline Characteristics of recursion Recursion

More information