DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N.

Similar documents
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N.

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

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger.

Lecture 5: Sorting Part A

Multiple-choice (35 pt.)

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Sorting and Selection

1. Covered basics of a simple design technique (Divideand-conquer) 2. Next, more sorting algorithms.

CS61BL. Lecture 5: Graphs Sorting

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. Fall 2016.

COMP Data Structures

Tirgul 4. Order statistics. Minimum & Maximum. Order Statistics. Heaps. minimum/maximum Selection. Overview Heapify Build-Heap

Next. 1. Covered basics of a simple design technique (Divideand-conquer) 2. Next, more sorting algorithms.

CS 310 Advanced Data Structures and Algorithms

EECS 2011M: Fundamentals of Data Structures

4.4 Algorithm Design Technique: Randomization

CS61B Lectures # Purposes of Sorting. Some Definitions. Classifications. Sorting supports searching Binary search standard example

Data Structures and Algorithms Week 4

O(n): printing a list of n items to the screen, looking at each item once.

COS 226 Midterm Exam, Spring 2009

Sorting. Bubble Sort. Pseudo Code for Bubble Sorting: Sorting is ordering a list of elements.

08 A: Sorting III. CS1102S: Data Structures and Algorithms. Martin Henz. March 10, Generated on Tuesday 9 th March, 2010, 09:58

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

8. Binary Search Tree

Unit 6 Chapter 15 EXAMPLES OF COMPLEXITY CALCULATION

21# 33# 90# 91# 34# # 39# # # 31# 98# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9# 10# #

Sorting. Popular algorithms: Many algorithms for sorting in parallel also exist.

Algorithms and Data Structures (INF1) Lecture 7/15 Hua Lu

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n.

Instructions. Definitions. Name: CMSC 341 Fall Question Points I. /12 II. /30 III. /10 IV. /12 V. /12 VI. /12 VII.

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort?

ECE368 Exam 2 Spring 2016

Data Structures and Algorithms

Comparisons. Heaps. Heaps. Heaps. Sorting Revisited. Heaps. So far we talked about two algorithms to sort an array of numbers

4. Sorting and Order-Statistics

CS 315 Data Structures Spring 2012 Final examination Total Points: 80

COMP2012H Spring 2014 Dekai Wu. Sorting. (more on sorting algorithms: mergesort, quicksort, heapsort)

CSE 3101: Introduction to the Design and Analysis of Algorithms. Office hours: Wed 4-6 pm (CSEB 3043), or by appointment.

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

DO NOT REPRODUCE. CS61B, Fall 2008 Test #3 (revised) P. N. Hilfinger

CSE373 Fall 2013, Final Examination December 10, 2013 Please do not turn the page until the bell rings.

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

CS 2412 Data Structures. Chapter 10 Sorting and Searching

CS61B, Fall 2015 Final Examination (with corrections) P. N. Hilfinger

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17

Practical Session #11 - Sort properties, QuickSort algorithm, Selection

Data Structures and Algorithms Chapter 4

SAMPLE OF THE STUDY MATERIAL PART OF CHAPTER 6. Sorting Algorithms

Unit-2 Divide and conquer 2016

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

CHAPTER 7 Iris Hui-Ru Jiang Fall 2008

QuickSort

COMP 250 Fall Homework #4

We can use a max-heap to sort data.

CS-141 Exam 2 Review April 4, 2015 Presented by the RIT Computer Science Community

BM267 - Introduction to Data Structures

Better sorting algorithms (Weiss chapter )

7. Sorting I. 7.1 Simple Sorting. Problem. Algorithm: IsSorted(A) 1 i j n. Simple Sorting

How many leaves on the decision tree? There are n! leaves, because every permutation appears at least once.

Overview of Sorting Algorithms

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Jana Kosecka. Linear Time Sorting, Median, Order Statistics. Many slides here are based on E. Demaine, D. Luebke slides

DO NOT. In the following, long chains of states with a single child are condensed into an edge showing all the letters along the way.

SORTING. Comparison of Quadratic Sorts

CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators)

Data Structures in Java

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

Classic Data Structures Introduction UNIT I

II (Sorting and) Order Statistics

Searching in General

Randomized Algorithms: Selection

COT 5407: Introduction. to Algorithms. Giri NARASIMHAN. 1/29/19 CAP 5510 / CGS 5166

Properties of a heap (represented by an array A)

Name: UTLN: CS login: Comp 15 Data Structures Midterm 2018 Summer

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

CSE 373 Final Exam 3/14/06 Sample Solution

CS S-11 Sorting in Θ(nlgn) 1. Base Case: A list of length 1 or length 0 is already sorted. Recursive Case:

Data Structures and Algorithms. Roberto Sebastiani

Module 2: Classical Algorithm Design Techniques

CS Sorting Terms & Definitions. Comparing Sorting Algorithms. Bubble Sort. Bubble Sort: Graphical Trace

Practical Session 10 - Huffman code, Sort properties, QuickSort algorithm, Selection

CISC 621 Algorithms, Midterm exam March 24, 2016

CS61B, Fall 2011 Final Examination (corrected) P. N. Hilfinger

Sorting. Chapter 12. Exercises

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

CPSC 311 Lecture Notes. Sorting and Order Statistics (Chapters 6-9)

Sorting is ordering a list of objects. Here are some sorting algorithms

Practice final for EECS 380, 2001: Prof Markov

Lecture Summary CSC 263H. August 5, 2016

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g)

DATA STRUCTURES AND ALGORITHMS

Chapter 10. Sorting and Searching Algorithms. Fall 2017 CISC2200 Yanjun Li 1. Sorting. Given a set (container) of n elements

CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting. Aaron Bauer Winter 2014

COMP Analysis of Algorithms & Data Structures

Selection, Bubble, Insertion, Merge, Heap, Quick Bucket, Radix

lecture notes September 2, How to sort?

Quicksort. Repeat the process recursively for the left- and rightsub-blocks.

Transcription:

CS61B Fall 2011 UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division Test #2 Solutions P. N. Hilfinger 1. [3 points] Consider insertion sort, merge sort, and quicksort. For each algorithm, what is the worst-case asymptotic bound on the running time for a list of N elements if you know additionally that: the input is already sorted? the input is reversely sorted? the input is a list containing N copies of the same number? Condition Insertion Sort Merge Sort Quicksort Notes Sorted Θ(N) Θ(N lg N) Θ(N lg N) The quicksort figure assumes reasonable pivoting (say about the median of first, middle, and last values). Technically, without this provision, the answer O(N 2 ) also works. Reverse sorted Θ(N 2 ) Θ(N lg N) Θ(N lg N) See preceding note. N copies Θ(N) Θ(N lg N) Θ(N 2 ) For quicksort, the pivot step will put almost all elements in one partition. 1

2 2. [3 points] We want a data structure,t, on which we can perform the following operations with the given complexity (N being the number of elements already inserted in the data structure): insert(x, T) insert a new element in O(lg N) time. contains(x, T) check if the structure contains element x in O(lg N) time. delete(k, T) delete the k th smallest element in O(lg N) time, where we take k to be a constant. Out of all the data structures given below, which one(s) would you pick? For any you reject, explain briefly. Simply circle those that you accept; no explanation is necessary. a heap No: containment check takes O(N). Delete is tricky, but technically can be done with a large constant factor (order 2 k ). a red-black tree Yes. a binary search tree No: only works if data is such that tree remains balanced. an unsorted linked list No: contains and delete require O(N). a sorted linked list No: contains and delete require O(N) (because access to general element requires O(N).) an unsorted array No: all operations require O(N). a sorted array No: contains requires O(lg N), but insert and delete require O(N). a hash table (nothing said about the hash function) No: without guarantees on the hash function, same as unsorted list.

3 30 5 17 3. [2 points] In doing Project #2, Bill Bucket has written the following function: /** Returns a copy of A that is unaffected by subsequent operations on * A. */ public static int[][] copy(int[][] A) { int[][] result = new int[a.length][]; for (int i = 0; i < A.length; i += 1) { result[i] = A[i]; return result; Devise a unit test that shows that this method does not work (does not fulfill its documentation). @Test public void checkcopy() { int[][] A = { { 1, 2 ; int[][] C = copy(a); A[0][0] = 0; assertarrayequals(new int { 1, 2, C[0]); 4. [3 points] Starting from the max-heap on the left, we remove the largest element and insert 20. The resulting heap is shown on the right. Assume that all values are unique and that 20 is not in the original heap. 40 15 3 10 17 5 10 30 20 3 15 Fill in the blank nodes in both heaps to show one possible way that this result could come about.

4 5. [1 point] What non-mathematical property do the numbers 31, 45, 66, 99, and 500 have in common? Solution: The numbers are also names of card games. 6. [2 points] Show the steps taken by quicksort on the following unordered list, assuming that the pivot node is always the first item in the (sub)list being sorted, and the array is sorted in place. 36 22 15 56 48 90 72 06 To show a step, show the contents of the array at the beginning of each call (initial or recursive) on the quicksort procedure. Assume that we sort all the way down to the trivial case of subarrays of size 1. Solution: This solution uses the pivot method from the data-structure notes. The bars show the boundaries of the subsequences. We show the result of sorting all subsequences to save space. 36 22 15 56 48 90 72 06 Initial 06 22 15 36 48 90 72 56 06 22 15 36 48 90 72 56 06 15 22 36 48 56 72 90 06 15 22 36 48 56 72 90 Final

5 7. [4 points] A certain binary search tree representation uses the following representation /** A binary tree node. The empty tree is represented by null. */ class BinNode { /** Returns my left child. */ BinNode left() {... /** Returns my right child. */ BinNode right() {... /** Returns my parent, or null if I am the root of the entire * tree. */ BinNode parent() {... /** Returns my key value (label). */ ValueType label() {...... Fill in the following functions to conform to their comments. /** True iff B is the left child of another node. */ static boolean amleftchild(binnode b) { return b.parent()!= null && b.parent().left()==b; ; /** Returns the node in B s tree that contains the value next larger * than B s. Assumes that the tree I am part of is a binary search * tree and that all its values are unique. Returns null if G is * the node containing the largest value. Does not call label(). */ static BinNode next(binnode b) { if (b.right() == null) { while (b!= null) { if (amleftchild(b)) { return b.parent(); b = b.parent(); else { b = b.right(); while (b.left()!= null) { b = b.left(); return b;

6 8. [2 points] Consider a hash table that uses a very good hashing function one that (miraculously) always distributes keys evenly across the bins in the table. Assuming the hash table expands at need to maintain a load factor of 3, What can you say about the worst-case time for adding an item to the table when it contains N items to begin with? Solution: Because the table may have to be resized, O(N). What can you say about the worst-case time for adding N items to the table when it contains N items to begin with? Solution: Θ(N). Given the assumptions, insertion requires amortized constant time. 9. [1 point] I create a list of integers by calling semirandomlist(b, 10), using the following method: static void semirandomlist(int[] A, int jiggle) { Random R = new Random(); for (int i = 0; i < A.length; i += 1) { A[i] = i + R.nextInt(jiggle); (The nextint(jiggle) call produces a random integer 0 and <jiggle.) Having done this, I sort B using insertion sort. What can you say about the time required to do so? Be as precise as possible. Solution: An entry at position k can only be out of order with respect to the entries at positions i for which k 10 < i < k + 10. This limits the total number of inversions, and therefore the running time of insertion sort, to roughly 10N.