How many times is the loop executed? middle = (left+right)/2; if (value == arr[middle]) return true;

Similar documents
This lecture. Abstract Data Types (ADTs) The Stack ADT ( 4.2) Stacks. Stack Interface in Java. Exceptions. Abstract data types Stacks Queues

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 ( 4.2.1) Applications of Stacks ( 4.2.3) Array-based implementation ( 4.2.2) Growable array-based stack.

1/18/12. Chapter 5: Stacks, Queues and Deques. Stacks. Outline and Reading. Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University

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

Foundations of Data Structures

Stacks Goodrich, Tamassia

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

HOWDY! WELCOME TO CSCE 221 DATA STRUCTURES AND ALGORITHMS

COMP9024: Data Structures and Algorithms

Stacks Goodrich, Tamassia Stacks

Stacks. Lecture6: Stacks. Stack Operations. Stack Interface in Java

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

Data Structures Lecture 5

Stacks Goodrich, Tamassia, Goldwasser Stacks

Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists

Lecture 3 Linear Data Structures

Lecture 3 Linear Data Structures

csci 210: Data Structures Stacks and Queues

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

The Java Virtual Machine. Compiler construction The structure of a frame. JVM stacks. Lecture 2

a Not yet implemented in current version SPARK: Research Kit Pointer Analysis Parameters Soot Pointer analysis. Objectives

Queues COL 106. Slides by Amit Kumar, Shweta Agrawal

Lecture 3 Linear Data Structures

GARBAGE COLLECTION METHODS. Hanan Samet

Monitors. Lecture 6. A Typical Monitor State. wait(c) Signal and Continue. Signal and What Happens Next?

DataStruct 5. Stacks, Queues, and Deques

dc - Linux Command Dc may be invoked with the following command-line options: -V --version Print out the version of dc

3/1/18. Overview. Program Representations. Abstract Syntax Tree (AST) Eclipse JDT. Java Model. The Tree Structure of Java Project[2]

DYNAMIC STORAGE ALLOCATION. Hanan Samet

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees

CT 229 Object-Oriented Programming Continued

Query Language #1/3: Relational Algebra Pure, Procedural, and Set-oriented

CMSC 132: Object-Oriented Programming II. Stack and Queue

THE THETA BLOCKCHAIN

Standard ADTs. Lecture 19 CS2110 Summer 2009

CPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

CS 5114: Theory of Algorithms. Sorting. Insertion Sort. Exchange Sorting. Clifford A. Shaffer. Spring 2010

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1

Lecture #22 Pipelining II, Cache I

A Memory Efficient Array Architecture for Real-Time Motion Estimation

2D Transformations. Why Transformations. Translation 4/17/2009

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

COEN-4730 Computer Architecture Lecture 2 Review of Instruction Sets and Pipelines

You Are Here! Review: Hazards. Agenda. Agenda. Review: Load / Branch Delay Slots 7/28/2011

Apply to be a Meiklejohn! tinyurl.com/meikapply

DYNAMIC STORAGE ALLOCATION. Hanan Samet

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

Basic Data Structures

Getting Started PMW-EX1/PMW-EX3. 1 Rotate the grip with the RELEASE button pressed. Overview. Connecting the Computer and PMW-EX1/EX3

CENG 3420 Computer Organization and Design. Lecture 07: MIPS Processor - II. Bei Yu

Basic Data Structures 1 / 24

Building Java Programs

Lecture 27: Voronoi Diagrams

Time allowed : 3 hours Maximum Marks: 70

ITI Introduction to Computing II

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

Data Abstraction and Specification of ADTs

Pledge: Signature:

Linked Structures. See Section 3.2 of the text.

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request.

Any modern computer system will incorporate (at least) two levels of storage:

CSE 143. Lecture 4: Stacks and Queues

Image Enhancement in the Spatial Domain. Spatial Domain

ACT GLOBAL OPTIMIZATION COMPETITION

University of Waterloo Department of Electrical and Computer Engineering ECE250 Algorithms and Data Structures Fall 2014

CS 2461: Computer Architecture 1 Program performance and High Performance Processors

Configuring RSVP-ATM QoS Interworking

CS 61C: Great Ideas in Computer Architecture (Machine Structures) Instruc>on Level Parallelism

CSC148 Week 2. Larry Zhang

CS171 Midterm Exam. October 29, Name:

Lecture # 04. Image Enhancement in Spatial Domain

COSC 6385 Computer Architecture. - Pipelining

LIFO : Last In First Out

CS 61C: Great Ideas in Computer Architecture Instruc(on Level Parallelism: Mul(ple Instruc(on Issue

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

Lecture 8 Introduction to Pipelines Adapated from slides by David Patterson

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

== isn t always equal?

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Assignment 1. Check your mailbox on Thursday! Grade and feedback published by tomorrow.

Conversion Functions for Symmetric Key Ciphers

n If S is in convex position, then thee ae exactly k convex k-gons detemined by subsets of S. In geneal, howeve, S may detemine fa fewe convex k-gons.

4.2. Co-terminal and Related Angles. Investigate

Class 21. N -body Techniques, Part 4

In order to learn which questions have been answered correctly: 1. Print these pages. 2. Answer the questions.

More Data Structures (Part 1) Stacks

Finding point-pairs. Find Closest Point from Dense Cloud

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

Modeling a shared medium access node with QoS distinction

CS61B Spring 2016 Guerrilla Section 2 Worksheet

arxiv: v4 [cs.ds] 7 Feb 2018

Data Structures G5029

data structures and algorithms lecture 6

UNION FIND. naïve linking link-by-size link-by-rank path compression link-by-rank with path compression context. An Improved Equivalence Algorithm

Accelerating Storage with RDMA Max Gurtovoy Mellanox Technologies

Stacks and Queues

Transcription:

This lectue Complexity o binay seach Answes to inomal execise Abstact data types Stacks ueues ADTs, Stacks, ueues 1 binayseach(int[] a, int value) { while (ight >= let) { { i (value < a[middle]) ight = middle-1; let = middle+1; etun alse; ADTs, Stacks, ueues 2 Complexity o binay seach Complexity o binay seach binayseach(int[] a, int value) { Let n be the size o aay while (ight >= let) { How many times is the loop executed? { i (value < a[middle]) ight = middle-1; let = middle+1; etun alse; ADTs, Stacks, ueues 3 binayseach(int[] a, int value) { Let n be the size o aay while (ight let) { How many times is the loop executed? n { n/2 (n/2)/2 i (value < a[middle]) ight = middle-1; ((n/2)/2)/2 let = middle+1; In the wost case, until ((n/2) )/2 = 1 x times, whee 2 x n and 2 x-1 < n etun alse; x is log 2 n, ounded up to an intege ADTs, Stacks, ueues 4 Example: n = 10, value = 19 Complexity o binay seach 0 1 2 3 4 5 6 7 8 9 let = 0, binayseach(int[] a, int value) { Let n be the size o aay ight= 9, 13 15 17 19 21 23 25 27 29 31 middle = 4 constant time let = 0, opeations: c 1 13 15 17 19 ight= 3, middle = 1 while (ight >= let) { loop executed log 2 n times let = 2, 17 19 ight= 3, middle = 2 { constant time 19 let = 3, i (value < a[middle]) ight = middle-1; opeations: c 2 ight= 3, let = middle+1; middle = 3 n = 10, log 2 10 ounded up to an intege is 4. t(n) = c 1 + c 2 log 2 n+ c 3 Hint: given n, look o the next lagest powe o 2 etun alse; constant time opeation: c 3 and take log 2 o that. ADTs, Stacks, ueues 5 ADTs, Stacks, ueues 6 1

Finally Pove that c 1 + c 2 log 2 n+ c 3 O(log 2 n). Need to ind n 0 and c such that o all n n 0, c 1 + c 2 log 2 n+ c 3 c log 2 n Let n 0 be 2; then o all n n 0, log 2 n 1. So, o all n n 0, c 1 + c 2 log 2 n+ c 3 c 1 log 2 n+ c 2 log 2 n+ c 3 log 2 n and o all n n 0, c 1 + c 2 log 2 n+ c 3 (c 1 + c 2 + c 3 ) log 2 n Set n 0 = 2 and c = c 1 + c 2 + c 3. n O(n 2 ) Pove that n is in O(n 2 ). Need to ind n 0 and c such that o all n n 0, n c n 2 Let n 0 be 1; then o all n n 0, log 2 n n and n n 2 So, o all n n 0, n 7n 2 + 10 n 2 + n 2 and o all n n 0, n (7 + 10 + 1) n 2 Set n 0 = 1 and c = 18. ADTs, Stacks, ueues 7 ADTs, Stacks, ueues 8 n O(n) I we wee to pove that n is in O(n), we d need to ind n 0 and c such that o all n n 0, n c n Fo all such n 0 and c it will also hold that o all n n 0, 7n 2 + 10n c n (note o n 1, log 2 n is positive) 7n + 10 c n (c-10)/7 Thee is obviously no such n 0 and c: whateve values o n 0 and c we ix, we can also ind n n 0 which is lage than (c-10)/7. O(log a n) = O(log b n) Suppose (n) is in O(log a n). We pove that it is in O(log b n). I (n) is in O(log a n), thee exist n 0 and c such that o all n n 0, (n) c log a n. We know that log a n = log a b log b n (see Math to eview) Fo example, log 2 64 = log 2 8 log 8 64 6 = 3 2 So, i (n) c log a n, then (n) c log a b log b n log a b is a constant acto, so we can deine a new constant c =clog a b and we have: o all n n 0, (n) c log b n, hence (n) is in O(log b n). ADTs, Stacks, ueues 9 ADTs, Stacks, ueues 10 Abstact Data Types (ADTs) Stacks An abstact data type (ADT) is an abstaction o a data stuctue An ADT speciies: Data stoed Opeations on the data Eo conditions associated with opeations Example: ADT modeling a simple stock tading system The data stoed ae buy/sell odes The opeations suppoted ae ode buy(stock, shaes, pice) ode sell(stock, shaes, pice) void cancel(ode) Eo conditions: Buy/sell a nonexistent stock Cancel a nonexistent ode ADTs, Stacks, ueues 11 ADTs, Stacks, ueues 12 2

The Stack ADT ( 4.2) The Stack ADT stoes abitay objects Insetions and deletions ollow the last-in ist-out scheme Think o a sping-loaded plate dispense Main stack opeations: push(object): insets an element object pop(): emoves and etuns the last inseted element Auxiliay stack opeations: object top(): etuns the last inseted element without emoving it intege size(): etuns the numbe o elements stoed boolean isempty(): indicates whethe no elements ae stoed Stack Inteace in Java Java inteace coesponding to ou Stack ADT Requies the deinition o class EmptyStackException Dieent om the built-in Java class java.util.stack public inteace Stack { public int size(); public boolean isempty(); public Object top() thows EmptyStackException; public void push(object o); public Object pop() thows EmptyStackException; ADTs, Stacks, ueues 13 ADTs, Stacks, ueues 14 Exceptions Attempting the execution o an opeation o ADT may sometimes cause an eo condition, called an exception Exceptions ae said to be thown by an opeation that cannot be executed In the Stack ADT, opeations pop and top cannot be peomed i the stack is empty Attempting the execution o pop o top on an empty stack thows an EmptyStackException Applications o Stacks Diect applications Page-visited histoy in a Web bowse Undo sequence in a text edito Chain o method calls in the Java Vitual Machine Indiect applications Auxiliay data stuctue o algoithms Component o othe data stuctues ADTs, Stacks, ueues 15 ADTs, Stacks, ueues 16 Method Stack in the JVM The Java Vitual Machine (JVM) keeps tack o the chain o active methods with a stack When a method is called, the JVM pushes on the stack a ame containing Local vaiables and etun value Pogam counte, keeping tack o the statement being executed When a method ends, its ame is popped om the stack and contol is passed to the method on top o the stack Allows o ecusion main() { int i = 5; oo(i); oo(int j) { int k; k = j+1; ba(k); ba(int m) { ba PC = 1 m = 6 oo PC = 3 j = 5 k = 6 main PC = 2 i = 5 ADTs, Stacks, ueues 17 Aay-based Stack A simple way o implementing the Stack ADT uses an aay We add elements om let to ight A vaiable keeps tack o the index o the top element S Algoithm size() etun t +1 Algoithm pop() i isempty() then thow EmptyStackException t t 1 etun S[t +1] 0 1 2 t ADTs, Stacks, ueues 18 3

Aay-based Stack (cont.) The aay stoing the stack elements may become ull A push opeation will then thow a FullStackException Limitation o the aaybased implementation Not intinsic to the Stack ADT S Algoithm push(o) i t = S.length 1 then thow FullStackException t t +1 S[t] o 0 1 2 t ADTs, Stacks, ueues 19 Peomance and Limitations Peomance Let n be the numbe o elements in the stack The space used is O(n) Each opeation uns in time O(1) Limitations The maximum size o the stack must be deined a pioi and cannot be changed Tying to push a new element into a ull stack causes an implementation-speciic exception ADTs, Stacks, ueues 20 Aay-based Stack in Java Paentheses Matching public class AayStack implements Stack { // holds the stack elements pivate Object S[ ]; // index to top element pivate int top = -1; // constucto public AayStack(int capacity) { S = new Object[capacity]); public Object pop() thows EmptyStackException { i isempty() thow new EmptyStackException ( Empty stack: cannot pop ); Object temp = S[top]; // acilitates gabage collection S[top] = null; top = top 1; etun temp; Each (, {, o [ must be paied with a matching ),, o [ coect: ( )(( )){([( )]) coect: ((( )(( )){([( )]) incoect: )(( )){([( )]) incoect: ({[ ]) incoect: ( ADTs, Stacks, ueues 21 ADTs, Stacks, ueues 22 Paentheses Matching Algoithm Algoithm PaenMatch(X,n): Input: An aay X o n tokens, each o which is eithe a gouping symbol, a vaiable, an aithmetic opeato, o a numbe Output: tue i and only i all the gouping symbols in X match Let S be an empty stack o i=0 to n-1 do i X[i] is an opening gouping symbol then S.push(X[i]) i X[i] is a closing gouping symbol then i S.isEmpty() then etun alse {nothing to match with i S.pop() does not match the type o X[i] then etun alse {wong type i S.isEmpty() then etun tue {evey symbol matched etun alse {some symbols wee neve matched ueues ADTs, Stacks, ueues 23 ADTs, Stacks, ueues 24 4

The ueue ADT ( 4.3) The ueue ADT stoes abitay objects Insetions and deletions ollow the ist-in ist-out scheme Insetions ae at the ea o the queue and emovals ae at the ont o the queue Main queue opeations: enqueue(object): insets an element at the end o the queue object dequeue(): emoves and etuns the element at the ont o the queue Auxiliay queue opeations: object ont(): etuns the element at the ont without emoving it intege size(): etuns the numbe o elements stoed boolean isempty(): indicates whethe no elements ae stoed Exceptions Attempting the execution o dequeue o ont on an empty queue thows an EmptyueueException ueue Example Opeation Output enqueue(5) (5) enqueue(3) (5, 3) dequeue() 5 (3) enqueue(7) (3, 7) dequeue() 3 (7) ont() 7 (7) dequeue() 7 () dequeue() eo () isempty() tue () enqueue(9) (9) enqueue(7) (9, 7) size() 2 (9, 7) enqueue(3) (9, 7, 3) enqueue(5) (9, 7, 3, 5) dequeue() 9 (7, 3, 5) ADTs, Stacks, ueues 25 ADTs, Stacks, ueues 26 Applications o ueues Diect applications Waiting lists, bueaucacy Access to shaed esouces (e.g., pinte) Multipogamming Indiect applications Auxiliay data stuctue o algoithms Component o othe data stuctues ADTs, Stacks, ueues 27 Aay-based ueue Use an aay o size N in a cicula ashion Two vaiables keep tack o the ont and ea index o the ont element index immediately past the ea element Aay location is kept empty nomal coniguation wapped-aound coniguation 012 ADTs, Stacks, ueues 28 ueue Opeations We use the modulo opeato (emainde o division) Algoithm size() etun (N + ) mod N Algoithm isempty() etun ( = ) ueue Opeations (cont.) Opeation enqueue thows an exception i the aay is ull This exception is implementationdependent Algoithm enqueue(o) i size() = N 1 then thow FullueueException [] o ( + 1) mod N 012 012 ADTs, Stacks, ueues 29 ADTs, Stacks, ueues 30 5

ueue Opeations (cont.) Opeation dequeue thows an exception i the queue is empty This exception is speciied in the queue ADT 012 Algoithm dequeue() i isempty() then thow EmptyueueException o [] ( + 1) mod N etun o ueue Inteace in Java Java inteace coesponding to ou ueue ADT Requies the deinition o class EmptyueueException No coesponding built-in Java class public inteace ueue { public int size(); public boolean isempty(); public Object ont() thows EmptyueueException; public void enqueue(object o); public Object dequeue() thows EmptyueueException; ADTs, Stacks, ueues 31 ADTs, Stacks, ueues 32 Application: Round Robin Schedules We can implement a ound obin schedule using a queue,, by epeatedly peoming the ollowing steps: 1. e =.dequeue() 2. Sevice element e 3..enqueue(e) The ueue 1. Deque the next element 2. Sevice the next element 3. Enqueue the seviced element Shaed Sevice ADTs, Stacks, ueues 33 6