Data Structures and Algorithms, Winter term 2017 Practice Assignment 7

Size: px
Start display at page:

Download "Data Structures and Algorithms, Winter term 2017 Practice Assignment 7"

Transcription

1 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 LinkList class provided to you on the website, adding the following methods: void insertlast(object o): inserts an object o at the end of the linked list. Your implementation should be an internal recursive one. public void insertlastrec(object o) if (head == null) head = new Link(o); else insertlastrec(head, o); public void insertlastrec(link l, Object o) if (l.next == null) l.next = new Link(o); else insertlastrec(l.next, o); void insertlast(object o): inserts an object o at the end of the linked list. Your implementation should be an external one. public static void insertlast(linklist l, Object o) LinkList tmp = new LinkList(); while(!l.isempty()) tmp.insertfirst(l.removefirst()); tmp.insertfirst(o); while(!tmp.isempty()) l.insertfirst(tmp.removefirst()); Object removelast(): removes and returns the last element from the linked list. Your implementation should be an external one. public static Object removelast(linklist l) LinkList tmp = new LinkList(); while(!l.isempty()) tmp.insertfirst(l.removefirst()); Object res = tmp.removefirst(); while(!tmp.isempty()) l.insertfirst(tmp.removefirst()); return res; 1

2 Exercise 7-2 Reverse Write a Java method reverse that takes as input a linked list of integers and reverses it. For example if the input list is: 1, 2, 3, 8, 10, 15 then reverse should return the list: 15, 10, 8, 3, 2, 1 a) Implement the method as an instance method of the class LinkList public LinkList reverse1() LinkList revlist = new LinkList(); while(current!= null) Link l = new Link(current.data); l.next = revlist.head; revlist.head = l; return revlist; The following solution stores the reversed values in the original list: public void reverse2() LinkList revlist = new LinkList(); while(current!= null) Link l = new Link(current.data); l.next = revlist.head; revlist.head = l; head = revlist.head; b) Implement the method externally in a class LinkListApp public static LinkList reverse1(linklist list) LinkList revlist = new LinkList(); while(!list.isempty()) revlist.insertfirst(list.removefirst()); return revlist; The following solution stores the reversed values in the original list: public static void reverse2(linklist list) LinkList revlist = new LinkList(); while(!list.isempty()) revlist.insertfirst(list.removefirst()); while(!revlist.isempty()) list.insertlast(revlist.removefirst()); 2

3 Exercise 7-3 Reverse in place Write a Java method reverse that takes as input a linked list of integers and reverses it without using any external data structures, only use the input linked list. The reverse should be done in place. For example if the input list is: 1, 2, 3, 8, 10, 15 then reverse should return the list: 15, 10, 8, 3, 2, 1 a) Implement the method as an instance method of the class LinkList public void reverseinplace() Link current = head.next; Link previous = head; while(current!=null) Link temp = current.next; current.next= previous; previous=current; current = temp; head.next=null; head=previous; Exercise 7-4 Remove Duplicates Write an external Java method removeduplicates that takes as input a linked list of integers sorted in ascending order and deletes any duplicate nodes from the list. For example, if the input list is: then removeduplicates should change the list to: 1, 2, 3, 3, 5, 7, 7, 15 1, 2, 3, 5, 7, 15 public static void removeduplicates(linklist s1) LinkList templist = new LinkList(); templist.insertlast(s1.removefirst()); while(!s1.isempty()) if(!s1.getfirst().equals(templist.getlast())) templist.insertlast(s1.removefirst()); else s1.removefirst(); while(!templist.isempty()) s1.insertlast(templist.removefirst()); Exercise 7-5 Count 3

4 a) Write an iterative method called countiter() that returns the total number of elements in a linked list, or 0 if the list is empty. public int countiter() int n = 0; for(link x = head; x!= null; x = x.next) n++; return n; Another solution using while loop: public int countiter2() int n = 0; Link x = head; while(x!=null) n++; x=x.next; return n; b) Write a recursive method called countrec() that returns the total number of elements in a linked list, or 0 if the list is empty. public int countrec() return countrechlp(head); public int countrechlp(link l) if(l == null) return 0; else return 1 + countrechlp(l.next); Exercise 7-6 Mix elements of a List Write an external iterative method static LinkList mix(linklist x) that rearranges the list x as follows: the first element is taken from the front followed by the first element from the end, then the second element from the front followed by the second from the end and so on. Example: The mix method invoked on the linked list 1, 2, 3, 4, 5, 6, 7 should return the linked list 1, 7, 2, 6, 3, 5, 4. public static LinkList mix(linklist x) LinkList result = new LinkList(); while(!x.isempty()) result.insertlast(x.removefirst()); if(!x.isempty()) result.insertlast(x.removelast()); return result; 4

5 Exercise 7-7 Cut a List Write a method static LinkList cut(linklist x) that divides the list x into two (roughly) equal halves and puts the second half at the front of the first half. Write an internal (instance) method void cutlist() that performs the same operation. Example: The cut method invoked on the linked list: 1, 2, 3, 4, 5, 6, 7 will return the linked list: 5, 6, 7, 1, 2, 3, 4 External implementation: static LinkList cut(linklist x) LinkList front = new LinkList(); LinkList back = new LinkList(); while(!x.isempty()) front.insertlast(x.removefirst()); if(!x.isempty()) back.insertfirst(x.removelast()); while(!back.isempty()) front.insertfirst(back.removelast()); return front; Internal implementation: public void cutlist() if (head==null) return; Link current=head; Link previous= null; int count=0; while (current!=null) count++; current=head; for (int i=1; i<count/2 +count%2; i++) current=current.next; previous = current; while (current.next!=null) current.next = head; head = previous.next; previous.next = null; 5

6 Exercise 7-8 Splitting a List Write a java method frontbacksplit that takes as input a linked list of integers. The method should split the list into two sublists: one for the front half and one for the back half and print each. If the number of elements is odd, then the extra element should be placed into the front list. Note that your method should not alter the original list; instead, it should just print the contents of the two lists. For example, if the input list is then frontbacksplit should print: 2, 3, 5, 7, 11 First sublist:2,3,5, Second sublist:7,11 Note: Getting this right for all cases is harder than it looks. You should check your solution against a few cases (length = 2, length = 3, length = 4)to make sure that the list gets split correctly in all cases. If it works right for length = 4, then it will probably work right for length = public static void frontbacksplit(linklist list) int count = 0; LinkList temp = new LinkList(); while (!list.isempty()) temp.insertlast(list.removefirst()); count++; LinkList sublist1 = new LinkList(); LinkList sublist2 = new LinkList(); for (int i = 0;i < (count + 1)/2;i++) Object o = temp.removefirst(); list.insertlast(o); sublist1.insertlast(o); while (!temp.isempty()) Object o = temp.removefirst(); list.insertlast(o); sublist2.insertlast(o); System.out.print("First sublist:"); System.out.print(subList1.toString()+" "); System.out.print("Second sublist: "); System.out.print(subList2.toString()+" "); System.out.println(); Exercise 7-9 Alternating Split Write a Java method alternatingsplit that takes as input a linked list of characters and divides its nodes to make two smaller lists. The sublists should be made from the alternating elements in the original list. Your method should not alter the original list, just create two new lists and print them. For example, if the input list is: then alternatingsplit should print: a, b, c, d, e 6

7 First sublist: a, c, e, Second sublist:b, d public static void alternatingsplit(linklist list) LinkList sublist1 = new LinkList(); LinkList sublist2 = new LinkList(); LinkList templist = new LinkList(); int count = 0; if(list.isempty()) System.out.print("List is empty"); return; while(!list.isempty()) Object temp = list.removefirst(); if(count % 2 == 0) sublist1.insertlast(temp); else templist.insertlast(temp); count++; sublist2.insertlast(temp); while(!templist.isempty()) list.insertlast(templist.removefirst()); System.out.print("First sublist: "); System.out.print(subList1.toString()+" "); System.out.print("Second sublist: "); System.out.print(subList2.toString()+" "); System.out.println(); Exercise 7-10 Max of a list Write an iterative method max that takes a linked list as input, and returns the value of the maximum key in the linked list. Assume all keys are positive integers, and return null if the list is empty. Implement the method both externally and internally. External implementation: public static Object max(linklist l) if(l.isempty()) return null; Comparable max = (Comparable)l.removeFirst(); while(!l.isempty()) Object item = l.removefirst(); if(max.compareto(item) < 0) max = (Comparable)item; return max; Internal implementations: /*** max internal iterative ************************/ public Object max() if (head == null) return null; Comparable max = (Comparable)head.data; 7

8 Link current = head.next; while (current!= null) if (max.compareto(current.data) < 0) max = (Comparable)current.data; return max; /*** max internal recursive ************************/ public Object maxrec() if (head == null) return null; return maxrec(head); public Object maxrec(link l) if (l.next == null) return l.data; Comparable maxrest = (Comparable)maxRec(l.next); if (maxrest.compareto(l.data) > 0) return maxrest; return l.data; Exercise 7-11 Contains Implement an iterative internal method boolean contains(object o) inside class LinkedList which returns true if the linked list contains an object equal to Object o, and false otherwise. public boolean contains(object o) while(current!= null) if(current.data.equals(o)) return true; return false; Alternative implementation using for-loop: public boolean contains2(object o) for (current!= null;current = current.next) if (current.data.equals(o)) return true; return false; Implement a recursive internal method boolean containsrec(object o) which performs the same function. public boolean containsrec(object o) return containsrec(head, o); public boolean containsrec(link l, Object o) if (l == null) return false; 8

9 if (l.data.equals(o)) return true; return containsrec(l.next, o); Exercise 7-12 Implement each of the following methods both internally (using reference manipulation) and externally (using the methods available in the LinkList class). merge that merges two linked lists equals that returns true if the two lists consist of the same elements intersection that returns the intersection of two linked lists difference that returns the difference of two linked lists union that returns the union of two linked lists Implement all methods both internally inside the LinkList class and externally inside LinkListApp class. a) Implementation of all the methods internally as instance methods of the class LinkList public LinkList merge(linklist l) LinkList o=new LinkList(); o.head=head; Link current=head; while(current.next!=null) current=current.next; current.next=l.head; return o; public boolean equals(linklist l) Link c1 = this.head; Link c2 = l.head; while(c1!= null && c2!= null) if(!c1.data.equals(c2.data)) return false; c1 = c1.next; c2 = c2.next; return c1 == null && c2 == null; public boolean contains(object o) while(current!= null) if(current.data.equals(o)) return true; return false; public LinkList intersection(linklist l) LinkList result = new LinkList(); while(current!= null) 9

10 if(l.contains(current.data)) result.insertlast(current.data); return result; public LinkList difference(linklist l) LinkList result = new LinkList(); while(current!= null) if(!l.contains(current.data)) result.insertlast(current.data); return result; public LinkList union(linklist l) return this.difference(l).merge(l); b) Implementation of all the methods externally in the class LinkListApp public static LinkList merge(linklist x,linklist y) LinkList z=new LinkList(); while(!x.isempty()) z.insertlast(x.removefirst()); while(!y.isempty()) z.insertlast(y.removefirst()); return z; public static boolean equals(linklist l1, LinkList l2) LinkList temp1 = new LinkList(); LinkList temp2 = new LinkList(); boolean equal = true; while(!l1.isempty() &&!l2.isempty() && equal) Object o1 = l1.removefirst(); Object o2 = l2.removefirst(); if(!o1.equals(o2)) equal = false; temp1.insertfirst(o1); temp2.insertfirst(o2); if(equal) equal = l1.isempty() && l2.isempty(); while(!temp1.isempty()) l1.insertfirst(temp1.removefirst()); while(!temp2.isempty()) l2.insertfirst(temp2.removefirst()); return equal; public static LinkList intersection(linklist x,linklist y) LinkList z=new LinkList(); LinkList temp=new LinkList(); while(!x.isempty()) Object k=x.removefirst(); while(!y.isempty()) 10

11 temp.insertlast(y.getfirst()); if(k.equals(y.removefirst())) z.insertlast(k); break; while(!temp.isempty()) y.insertlast(temp.removefirst()); return z; public static LinkList difference(linklist x,linklist y) LinkList z=new LinkList(); LinkList temp=new LinkList(); while(!x.isempty()) Object k=x.removefirst(); boolean flag=true; while(!y.isempty()) temp.insertlast(y.getfirst()); if(k.equals(y.removefirst())) flag=false; break; if(flag) z.insertlast(k); while(!temp.isempty()) y.insertlast(temp.removefirst()); return z; public static LinkList union(linklist x,linklist y) return merge(difference(x, y), y); 11

Data Structures and Algorithms, Winter term 2018 Practice Assignment 3

Data Structures and Algorithms, Winter term 2018 Practice Assignment 3 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

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

CMSC 132, Object-Oriented Programming II Summer Lecture 6:

CMSC 132, Object-Oriented Programming II Summer Lecture 6: CMSC 132, Object-Oriented Programming II Summer 2017 Lecturer: Anwar Mamat Lecture 6: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 6.1 Singly

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

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

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

Introduction. Reference

Introduction. Reference Introduction Data Structures - Linked Lists 01 Dr TGI Fernando 1 2 Problems with arrays Unordered array - searching is slow, deletion is slow Ordered array - insertion is slow, deletion is slow Arrays

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

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

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018 CSC 172 Data Structures and Algorithms Lecture #9 Spring 2018 SINGLY LINKED LIST 3.1.3 Linked lists We will consider these for Singly linked lists Doubly linked lists Basic Singly Linked List class Node

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

Fun facts about recursion

Fun facts about recursion Outline examples of recursion principles of recursion review: recursive linked list methods binary search more examples of recursion problem solving using recursion 1 Fun facts about recursion every loop

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

Sorting. Task Description. Selection Sort. Should we worry about speed?

Sorting. Task Description. Selection Sort. Should we worry about speed? Sorting Should we worry about speed? Task Description We have an array of n values in any order We need to have the array sorted in ascending or descending order of values 2 Selection Sort Select the smallest

More information

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

Introduction to Computer Science II CS S-20 Linked Lists IV

Introduction to Computer Science II CS S-20 Linked Lists IV Introduction to Computer Science II CS112-2012S-20 Linked Lists IV David Galles Department of Computer Science University of San Francisco 20-0: Doubly Linked List Deleting from (and inserting into!) a

More information

LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015

LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015 LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015 1 administrivia 2 -assignment 5 due tonight at midnight -assignment 6 is out -YOU WILL BE SWITCHING PARTNERS! 3 assignment

More information

Solution to Test of Computer Science 203x Level Score: / 100 Time: 100 Minutes

Solution to Test of Computer Science 203x Level Score: / 100 Time: 100 Minutes Solution to Test of Computer Science 203x Level Score: / 100 Time: 100 Minutes PART I: Multiple Choice (3 points each) Note: The correct answer can be any combination of A, B, C, D. Example, Sample Question:

More information

S O R T I N G Sorting a list of elements implemented as an array. In all algorithms of this handout the sorting of elements is in ascending order

S O R T I N G Sorting a list of elements implemented as an array. In all algorithms of this handout the sorting of elements is in ascending order S O R T I N G Sorting is interpreted as arranging data in some particular order. In this handout we discuss different sorting techniques for a list of elements implemented as an array. In all algorithms

More information

n 1 x i = xn 1 x 1. i= (2n 1) = n 2.

n 1 x i = xn 1 x 1. i= (2n 1) = n 2. Questions 1. Use mathematical induction to prove that, for any n 1 n 1 x i = xn 1 x 1. (Recall that I proved it in a different way back in lecture 2.) 2. Use mathematical induction to prove that, for all

More information

COL106: Data Structures and Algorithms. Ragesh Jaiswal, IIT Delhi

COL106: Data Structures and Algorithms. Ragesh Jaiswal, IIT Delhi Stack and Queue How do we implement a Queue using Array? : A collection of nodes with linear ordering defined on them. Each node holds an element and points to the next node in the order. The first node

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

Final Exam Data Structure course. No. of Branches (5)

Final Exam Data Structure course. No. of Branches (5) Page ١of 5 College Of Science and Technology Khan younis - Palestine Computer Science & Inf. Tech. Information Technology Data Structure (Theoretical Part) Time: 2 Hours Name: ID: Mark: Teacher 50 Mahmoud

More information

CSE 143, Winter 2009 Sample Midterm Exam #2

CSE 143, Winter 2009 Sample Midterm Exam #2 CSE 143, Winter 2009 Sample Midterm Exam #2 1. Stacks and Queues. Write a method interleave that accepts a queue of integers as a parameter and rearranges the elements by alternating the elements from

More information

CS 112 Midterm Exam Fall 2016

CS 112 Midterm Exam Fall 2016 Name: CS 112 Midterm Exam Fall 2016 B There are 7 problems on the exam. The first and last are mandatory, and you may eliminate any one of problems 2 6 by drawing an X through them. Problem 1 is worth

More information

Sorting Algorithms Day 2 4/5/17

Sorting Algorithms Day 2 4/5/17 Sorting Algorithms Day 2 4/5/17 Agenda HW Sorting Algorithms: Review Selection Sort, Insertion Sort Introduce MergeSort Sorting Algorithms to Know Selection Sort Insertion Sort MergeSort Know their relative

More information

DNHI Homework 3 Solutions List, Stacs and Queues

DNHI Homework 3 Solutions List, Stacs and Queues Solutions List, Stacs and Queues Problem 1 Given the IntegerQueue ADT below state the return value and show the content of the, initially empty, queue of Integer objects after each of the following operations.

More information

Suppose that we have linked list of integers where each node is represented as: // An item in the list.

Suppose that we have linked list of integers where each node is represented as: // An item in the list. Linked List Suppose that we have linked list of integers where each node is represented as: class ListNode { int item; // An item in the list. ListNode next; // Pointer to next item in the list. This node

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

CS61B, Spring 2003 Discussion #15 Amir Kamil UC Berkeley 4/28/03

CS61B, Spring 2003 Discussion #15 Amir Kamil UC Berkeley 4/28/03 CS61B, Spring 2003 Discussion #15 Amir Kamil UC Berkeley 4/28/03 Topics: Sorting 1 Sorting The topic of sorting really requires no introduction. We start with an unsorted sequence, and want a sorted sequence

More information

Linked Lists and other Dynamic Data Structures

Linked Lists and other Dynamic Data Structures Linked Lists and other Dynamic Data Structures Arrays Fixed in size Allocated in advance within a contiguous memory block Look-up is fast Resizing and Deleting is hard (reallocate and copy) Dynamic Data

More information

Introduction to Computer Science, Winter Term Lab Exercise 6 Discussion:

Introduction to Computer Science, Winter Term Lab Exercise 6 Discussion: German University in Cairo Faculty of Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Rimon Elias Introduction to Computer Science, Winter Term 2013-2014 Lab Exercise 6 Discussion: 21.12.2013-26.12.2013

More information

Week - 04 Lecture - 02 Merge Sort, Analysis

Week - 04 Lecture - 02 Merge Sort, Analysis Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 04 Lecture - 02 Merge Sort, Analysis

More information

Introduction to Computer Science II CS S-18 Linked Lists

Introduction to Computer Science II CS S-18 Linked Lists Introduction to Computer Science II CS112-2012S-18 Linked Lists David Galles Department of Computer Science University of San Francisco 18-0: Linked Lists Linked List node Data Pointer to the next element

More information

Faster Sorting Methods

Faster Sorting Methods Faster Sorting Methods Chapter 9 Contents Merge Sort Merging Arrays Recursive Merge Sort The Efficiency of Merge Sort Iterative Merge Sort Merge Sort in the Java Class Library Contents Quick Sort The Efficiency

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

Intro to Programming II

Intro to Programming II 18-2: Arrays Intro to Programming II Linked Lists Chris Brooks Department of Computer Science University of San Francisco Previously we talked about using arrays to store sequences of data. Advantages:

More information

Chapter 10 - Notes Applications of Arrays

Chapter 10 - Notes Applications of Arrays Chapter - Notes Applications of Arrays I. List Processing A. Definition: List - A set of values of the same data type. B. Lists and Arrays 1. A convenient way to store a list is in an array, probably a

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

CSE 143 Lecture 14. Sorting

CSE 143 Lecture 14. Sorting CSE 143 Lecture 14 Sorting slides created by Marty Stepp and Ethan Apter http://www.cs.washington.edu/143/ Sorting sorting: Rearranging the values in an array or collection into a specific order (usually

More information

Sorting Pearson Education, Inc. All rights reserved.

Sorting Pearson Education, Inc. All rights reserved. 1 19 Sorting 2 19.1 Introduction (Cont.) Sorting data Place data in order Typically ascending or descending Based on one or more sort keys Algorithms Insertion sort Selection sort Merge sort More efficient,

More information

CSC 172 Data Structures and Algorithms. Lecture #8 Spring 2018

CSC 172 Data Structures and Algorithms. Lecture #8 Spring 2018 CSC 172 Data Structures and Algorithms Lecture #8 Spring 2018 Project 1 due tonight Announcements Project 2 will be out soon Q & A Reminder: For sharing your concern anonymously, you can always go to:

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 6 - Faster Sorting Methods Merge Sort Divides an array into halves Sorts the two halves, Then merges them into one sorted array. The algorithm for merge sort is usually

More information

Introduction to Computer Science II (CSI 1101)

Introduction to Computer Science II (CSI 1101) Introduction to Computer Science II (CSI 1101) Professor: M. Turcotte February 2002, duration: 75 minutes Identification Student name: last name: Section: Student number: initials: Signature: Instructions

More information

CSE 214 Computer Science II Final Review II

CSE 214 Computer Science II Final Review II CSE 214 Computer Science II Final Review II Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Linked List Problems Finding

More information

Key question: how do we pick a good pivot (and what makes a good pivot in the first place)?

Key question: how do we pick a good pivot (and what makes a good pivot in the first place)? More on sorting Mergesort (v2) Quicksort Mergesort in place in action 53 2 44 85 11 67 7 39 14 53 87 11 50 67 2 14 44 53 80 85 87 14 87 80 50 29 72 95 2 44 80 85 7 29 39 72 95 Boxes with same color are

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

protected BinaryNode root; } 02/17/04 Lecture 11 1

protected BinaryNode root; } 02/17/04 Lecture 11 1 Binary Search Trees // BinarySearchTree class // void insert( x ) --> Insert x // void remove( x ) --> Remove x // void removemin( ) --> Remove minimum item // Comparable find( x ) --> Return item that

More information

CS2110: Software Development Methods. Maps and Sets in Java

CS2110: Software Development Methods. Maps and Sets in Java CS2110: Software Development Methods Maps and Sets in Java These slides are to help with the lab, Finding Your Way with Maps Today s lab uses Maps (and Sets but just a little). Readings from textbook:

More information

Facebook. / \ / \ / \ Accenture Nintendo

Facebook. / \ / \ / \ Accenture Nintendo 1. Binary Tree Traversal Consider the following tree: +---+ 4 +---+ 1 9 / / +---+ 6 0 2 +---+ 3 8 \ \ \ \ 7 5 Fill in each of the traversals below : Pre-order: 4 1 6 3 7 0 8 5 9 2 In-order: 3 7 6 1 0 8

More information

We cover recursion in 150. Why do it again in 151?

We cover recursion in 150. Why do it again in 151? Recursion We cover recursion in 150. Why do it again in 151? First, good solutions to problems are often recursive. Here is a quick way to sort a list of objects: split the list in half, recursively sort

More information

Introduction to Computer Science II CS S-20 Linked Lists III

Introduction to Computer Science II CS S-20 Linked Lists III Introduction to Computer Science II CS112-2012S-20 Linked Lists III David Galles Department of Computer Science University of San Francisco 20-0: Linked List Previous Practical Example: removeat(int index)

More information

(Divide and Conquer) Electrical & Computer Engineering University of Waterloo Canada. February 14, Divide And Conquer

(Divide and Conquer) Electrical & Computer Engineering University of Waterloo Canada. February 14, Divide And Conquer ( ) Electrical & Computer Engineering University of Waterloo Canada February 14, 2007 Divide And BinarySearch is an (arguably degenerate) instance of a basic algorithm design pattern: Divide And 1. If

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

CS 307 Midterm 2 Spring 2008

CS 307 Midterm 2 Spring 2008 Points off 1 2 3 4 Total off Net Score Exam Number: CS 307 Midterm 2 Spring 2008 Name UTEID login name TA's Name: Mario Ruchica Vishvas (Circle One) Instructions: 1. Please turn off your cell phones and

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Searching data involves determining whether a value (referred to as the search key) is present in the data

More information

DATA STRUCTURES AND ALGORITHMS

DATA STRUCTURES AND ALGORITHMS DATA STRUCTURES AND ALGORITHMS Fast sorting algorithms Shellsort, Mergesort, Quicksort Summary of the previous lecture Why sorting is needed? Examples from everyday life What are the basic operations in

More information

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 Trimester 2, MID-TERM TEST COMP103 Introduction

More information

CS211, LECTURE 20 SEARCH TREES ANNOUNCEMENTS:

CS211, LECTURE 20 SEARCH TREES ANNOUNCEMENTS: CS211, LECTURE 20 SEARCH TREES ANNOUNCEMENTS: OVERVIEW: motivation naive tree search sorting for trees and binary trees new tree classes search insert delete 1. Motivation 1.1 Search Structure continuing

More information

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 MID YEAR COMP103 Introduction to Data

More information

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Spring What is your name?: (4 points for writing it on your answer sheet)

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Spring What is your name?: (4 points for writing it on your answer sheet) CS 102 - Introduction to Programming Midterm Exam #1 - Prof. Reed Spring 2008 What is your name?: (4 points for writing it on your answer sheet) There are two sections: I. True/False.....................

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 2008 What is your name?: There are three sections: I. True/False..............60 points; (30 questions, 2 points each) II. Multiple

More information

Programming Problems 22nd Annual Computer Science Programming Contest

Programming Problems 22nd Annual Computer Science Programming Contest Programming Problems 22nd Annual Computer Science Programming Contest Department of Mathematics and Computer Science Western Carolina University 5 April 2011 Problem One: Add Times Represent a time by

More information

CS 163 Practice Final Exam Winter 2012

CS 163 Practice Final Exam Winter 2012 CS 163 Practice Final Exam Winter 2012 The final exam is Saturday, 21 April. Any problem from either midterm or either practice midterm may (and often does) appear again on the final. In addition, make

More information

OF VICTORIA EXAMINATIONS- DECEMBER 2010 CSC

OF VICTORIA EXAMINATIONS- DECEMBER 2010 CSC Name: ID Number: UNIVERSITY OF VICTORIA EXAMINATIONS- DECEMBER 2010 CSC 225 - Algorithms and Data Structures: I Section A01 (CRN 1089) Instructor: Wendy Myrvold Duration: 3 hours TO BE ANSWERED ON THE

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

CS 307 Midterm 2 Fall 2008

CS 307 Midterm 2 Fall 2008 Points off 1 2 3 4 5 Total off Net Score Exam Number: CS 307 Midterm 2 Fall 2008 Name UTEID login name TA's Name: Mikie Ron Sarah (Circle One) Instructions: 1. Please turn off your cell phones and other

More information

Computer Science E-119 Fall Problem Set 1. Due before lecture on Wednesday, September 26

Computer Science E-119 Fall Problem Set 1. Due before lecture on Wednesday, September 26 Due before lecture on Wednesday, September 26 Getting Started Before starting this assignment, make sure that you have completed Problem Set 0, which can be found on the assignments page of the course

More information

Sorting. CSE 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation. CSE143 Au

Sorting. CSE 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation. CSE143 Au CSE 43 Java Sorting Reading: Ch. 3 & Sec. 7.3 Sorting Binary search is a huge speedup over sequential search But requires the list be sorted Slight Problem: How do we get a sorted list? Maintain the list

More information

Section Handout #5 Solutions

Section Handout #5 Solutions CS106B Spring Summer 2018 2017 Section Handout #5 Solutions Chris Gregg If you have any questions about the solutions to the problems in this handout, feel free to reach out to your section leader, Jason,

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

Do you remember any iterative sorting methods? Can we produce a good sorting method by. We try to divide and conquer: break into subproblems

Do you remember any iterative sorting methods? Can we produce a good sorting method by. We try to divide and conquer: break into subproblems MERGESORT 315 Sorting Recursively Do you remember any iterative sorting methods? How fast are they? Can we produce a good sorting method by thinking recursively? We try to divide and conquer: break into

More information

Lecture Notes 14 More sorting CSS Data Structures and Object-Oriented Programming Professor Clark F. Olson

Lecture Notes 14 More sorting CSS Data Structures and Object-Oriented Programming Professor Clark F. Olson Lecture Notes 14 More sorting CSS 501 - Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading for this lecture: Carrano, Chapter 11 Merge sort Next, we will examine two recursive

More information

CSEN 202 Introduction to Computer Programming

CSEN 202 Introduction to Computer Programming CSEN 202 Introduction to Computer Programming Lecture 4: Iterations Prof. Dr. Slim Abdennadher and Dr Mohammed Abdel Megeed Salem, slim.abdennadher@guc.edu.eg German University Cairo, Department of Media

More information

Sorting Algorithms. + Analysis of the Sorting Algorithms

Sorting Algorithms. + Analysis of the Sorting Algorithms Sorting Algorithms + Analysis of the Sorting Algorithms Insertion Sort What if first k elements of array are already sorted? 4, 7, 12, 5, 19, 16 We can shift the tail of the sorted elements list down and

More information

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Recursive Algorithms CS 180 Sunil Prabhakar Department of Computer Science Purdue University Recursive Algorithms Within a given method, we are allowed to call other accessible methods. It is also possible

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

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm cmpt-225 Sorting Sorting Fundamental problem in computing science putting a collection of items in order Often used as part of another algorithm e.g. sort a list, then do many binary searches e.g. looking

More information

Tutorial 2: Linked Lists

Tutorial 2: Linked Lists Tutorial 2: Linked Lists ? 2 Agenda Introduction of Linked List Arrays Vs Linked Lists Types of Linked Lists Singly Linked List Doubly Linked List Circular Linked List Operations Insertion Deletion 3 Data

More information

CSE 143 Lecture 16 (B)

CSE 143 Lecture 16 (B) CSE 143 Lecture 16 (B) Sorting reading: 13.1, 13.3-13.4 slides created by Marty Stepp http://www.cs.washington.edu/143/ Sorting sorting: Rearranging the values in an array or collection into a specific

More information

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting RMIT School of Computer Science and Information Technology Programming 2 Topic 8: Linked Lists, Basic Searching and Sorting Lecture Slides COPYRIGHT 2008 RMIT University. Original content by: Peter Tilmanis,

More information

Sorting. CSC 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation CSC Picture

Sorting. CSC 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation CSC Picture CSC 43 Java Sorting Reading: Sec. 9.3 Sorting Binary search is a huge speedup over sequential search But requires the list be sorted Slight Problem: How do we get a sorted list? Maintain the list in sorted

More information

CS S-20 Linked Lists IV 1

CS S-20 Linked Lists IV 1 CS112-2012S-20 Linked Lists IV 1 20-0: Doubly Linked List Deleting from (and inserting into!) a linked can be challenging because you need to find the node before the node you are looking for Once you

More information

CS205: Scalable Software Systems

CS205: Scalable Software Systems CS205: Scalable Software Systems Lecture 3 September 5, 2016 Lecture 3 CS205: Scalable Software Systems September 5, 2016 1 / 19 Table of contents 1 Quick Recap 2 Type of recursive solutions 3 Translating

More information

Model Solutions. COMP 103: Test April, 2013

Model Solutions. COMP 103: Test April, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 40 minutes

More information

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours: CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Tuesday 10:00 AM 12:00 PM * Wednesday 4:00 PM 5:00 PM Friday 11:00 AM 12:00 PM OR

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

Outline. Quadratic-Time Sorting. Linearithmic-Time Sorting. Conclusion. Bubble/Shaker Sort Insertion Sort Odd-Even Sort

Outline. Quadratic-Time Sorting. Linearithmic-Time Sorting. Conclusion. Bubble/Shaker Sort Insertion Sort Odd-Even Sort Outline Quadratic-Time Sorting Bubble/Shaker Sort Insertion Sort Odd-Even Sort Linearithmic-Time Sorting Heap Sort Merge Sort Quick Sort Conclusion Check out this link for animation of various sorting

More information

Advanced Computer Programming

Advanced Computer Programming Hazırlayan Yard. Doç. Dr. Mehmet Fidan ARRAYS A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays are has System.Array

More information

COMP103 Test. 5 Sept, 2007

COMP103 Test. 5 Sept, 2007 Family Name:.......................... Other Names:.......................... ID Number:............................ COMP103 Test 5 Sept, 2007 Instructions Time: 90 minutes. Answer all the questions. There

More information

Searching and Sorting

Searching and Sorting CS 211 SEARCH & SORT SEARCHING & SORTING Searching and Sorting Searching means that we have some collection of data, and we seek a particular value that might be contained within our collection. We provide

More information

Chapter 6: Using Arrays

Chapter 6: Using Arrays Chapter 6: Using Arrays Declaring an Array and Assigning Values to Array Array Elements A list of data items that all have the same data type and the same name Each item is distinguished from the others

More information

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School Chapter 12 Supplement: Recursion with Java 1.5 La Cañada High School Recursion: Definitions Recursion The process of a subprogram (method) calling itself. A clearly defined stopping state must exist. The

More information

1. Data types ( =13 points)

1. Data types ( =13 points) Software Development I Univ.-Prof. Dr. Alois Ferscha Examination, January 27, 2015 Last name: SAMPLE SOLUTION First name: Institute for Pervasive Computing Lecture hall: Seat: ID: SKZ: Points / Grade:

More information

Data Structures and Algorithms, Winter term 2018 Practice Assignment 11 H(N) = N % TABLESIZE 22, 91, 7, 881, 99, 15, 12, 31, 10

Data Structures and Algorithms, Winter term 2018 Practice Assignment 11 H(N) = N % TABLESIZE 22, 91, 7, 881, 99, 15, 12, 31, 10 German University in Cairo Media Engineering and Technology Prof. Dr. Slim Abdennadher Dr. Wael Abouelsaadat Data Structures and Algorithms, Winter term 2018 Practice Assignment 11 Exercise 11-1 Assume

More information

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Week 02 Module 06 Lecture - 14 Merge Sort: Analysis So, we have seen how to use a divide and conquer strategy, we

More information

Collections and Maps

Collections and Maps Software and Programming I Collections and Maps Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Array Lists Enhanced for Loop ArrayList and LinkedList Collection Interface Sets and

More information

Module 08: Searching and Sorting Algorithms

Module 08: Searching and Sorting Algorithms Module 08: Searching and Sorting Algorithms Topics: Searching algorithms Sorting algorithms 1 Application: Searching a list Suppose you have a list L. How could you determine if a particular value is in

More information

Homework Assignment #3. 1 (5 pts) Demonstrate how mergesort works when sorting the following list of numbers:

Homework Assignment #3. 1 (5 pts) Demonstrate how mergesort works when sorting the following list of numbers: CISC 4080 Computer Algorithms Spring, 2019 Homework Assignment #3 1 (5 pts) Demonstrate how mergesort works when sorting the following list of numbers: 6 1 4 2 3 8 7 5 2 Given the following array (list),

More information

CS18000: Problem Solving and Object-Oriented Programming

CS18000: Problem Solving and Object-Oriented Programming CS18000: Problem Solving and Object-Oriented Programming Recursion 28 March 2011 Prof. Chris Clifton Recursion Idea: break a problem down into small, similar sub-problems Write a method to solve first

More information