Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic



Similar documents
Binary search algorithm

Computer Science 210: Data Structures. Searching

Analysis of Binary Search algorithm and Selection Sort algorithm

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Algorithms. Margaret M. Fleck. 18 October 2010

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Data Structures. Algorithm Performance and Big O Analysis

Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park

To My Parents -Laxmi and Modaiah. To My Family Members. To My Friends. To IIT Bombay. To All Hard Workers

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Lecture Notes on Linear Search

Analysis of Algorithms I: Optimal Binary Search Trees

6. Standard Algorithms

External Sorting. Chapter 13. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Section IV.1: Recursive Algorithms and Recursion Trees

Introduction to Algorithms March 10, 2004 Massachusetts Institute of Technology Professors Erik Demaine and Shafi Goldwasser Quiz 1.

CSC 180 H1F Algorithm Runtime Analysis Lecture Notes Fall 2015

AP Computer Science AB Syllabus 1

Converting a Number from Decimal to Binary

Closest Pair of Points. Kleinberg and Tardos Section 5.4

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

GRID SEARCHING Novel way of Searching 2D Array

External Sorting. Why Sort? 2-Way Sort: Requires 3 Buffers. Chapter 13

Chapter 13: Query Processing. Basic Steps in Query Processing

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

6 March Array Implementation of Binary Trees

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

HW4: Merge Sort. 1 Assignment Goal. 2 Description of the Merging Problem. Course: ENEE759K/CMSC751 Title:

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

CS473 - Algorithms I

Biostatistics 615/815

Lecture 6: Binary Search Trees CSCI Algorithms I. Andrew Rosenberg

Binary Heap Algorithms

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Analysis of a Search Algorithm

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

DATA STRUCTURES USING C

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Sample Questions Csci 1112 A. Bellaachia

Binary Search Trees CMPSC 122

A Note on Maximum Independent Sets in Rectangle Intersection Graphs

Basic Programming and PC Skills: Basic Programming and PC Skills:

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Exam study sheet for CS2711. List of topics

Simple sorting algorithms and their complexity. Bubble sort. Complexity of bubble sort. Complexity of bubble sort. Bubble sort of lists

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Symbol Tables. Introduction

Data Structures. Topic #12

Lecture Notes on Binary Search Trees

4.2 Sorting and Searching

Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

Method To Solve Linear, Polynomial, or Absolute Value Inequalities:

For example, we have seen that a list may be searched more efficiently if it is sorted.

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Data Structures and Algorithms

CSI 333 Lecture 1 Number Systems

Why Use Binary Trees?

Many algorithms, particularly divide and conquer algorithms, have time complexities which are naturally

ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control

c. finding the largest element in a list of n numbers f. pen-and-pencil algorithm for multiplying two n-digit decimal integers

Using EXCEL Solver October, 2000

Lecture Notes on Binary Search Trees

Some programming experience in a high-level structured programming language is recommended.

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Introduction to Programming System Design. CSCI 455x (4 Units)

Analysis of Algorithms I: Binary Search Trees

Chapter 3. if 2 a i then location: = i. Page 40

THIS CHAPTER studies several important methods for sorting lists, both contiguous

6. Control Structures

Binary Heaps. CSE 373 Data Structures

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Near Optimal Solutions

Discrete Optimization

Loop Invariants and Binary Search

Algorithms and Data Structures

Pseudo code Tutorial and Exercises Teacher s Version

Stack Allocation. Run-Time Data Structures. Static Structures

AP Computer Science Java Mr. Clausen Program 9A, 9B

Searching & Sorting. Contents. I. Searching 6

Classification - Examples

Dynamic Programming. Lecture Overview Introduction

Introduction to Algorithms and Data Structures

Persistent Binary Search Trees

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Binary Multiplication

Data Structures and Data Manipulation

Randomized algorithms

Transcription:

1 Algorithm Analysis []: if-else statements, recursive algorithms COSC 011, Winter 004, Section N Instructor: N. Vlajic

Algorithm Analysis for-loop Running Time The running time of a simple loop for (int i=0; i<n; i++) { body; } is: RT(loop)*RT(body) = n*rt(body) if-else Running Time The running time of an if-else if (cond) S1 else S is never more than: RT worst-case = RT(cond) + max{rt(s1),rt(s)} is never less than: RT best-case = RT(cond) + min{rt(s1),rt(s)}

Algorithm Analysis (cont.) 3 Example 1 [ running time of a simple loop with a nested if-else ] int k=0; for (int i=0; i<n; i++) { /* outer_loop */ }; if even(i) { for (int j=0; j<n; j++) /* inner_loop */ else k *= ; k++; }; RT(n) = c + RT(outer_loop) * RT(body) = c + n * RT(body) RT worst-case (body) = c + max{ RT(inner_loop), c } = c + n*c RT(n) n*rt worst-case (n) = c+n*(c+n*c) RT(n) = O(n )

Algorithm Analysis (cont.) 4 What is the best-case RT of the given algorithm, i.e. lower bound on RT?? int k=0; for (int i=0; i<n; i++) { /* outer_loop */ }; if even(i) { for (int j=0; j<n; j++) /* inner_loop */ else k *= ; k++; }; RT best-case (n) = c + n * [ cond + min{ S 1, S }] = c + n*[c + c] RT(n) RT best-case (n) RT(n) = Ω(n)

Algorithm Analysis (cont.) 5 What is the actual RT of the given algorithm, in big-θ notation?? Assume n odd. int k=0; for (int i=0; i<n; i++) { (n+1)/ (n-1)/ }; if (i==0) { for (int j=0; j<n; j++) k++; }; if (i==) { for (int j=0; j<n; j++) k++; }; if (i==n-1) { for (int j=0; j<n; j++) k++; }; if (i==1) { k *= ; }; if (i==3) { k *= ; }; if (i==n) { k *= ; }; RT(n) = c + n + 1 n 1 n 1 ( c + c n) + ( c + c) = c + c + n = Θ(n )

Algorithm Analysis (cont.) 6 RT (n) c + c [n worst_case = + n] RT best_case (n) = c + n [ c] RT(n) = c n + c + n 1 = Θ(n ) The actual number of executed operations is less than what was roughly estimated, in the worst case analysis. However, it still increases quadratically with n!

Algorithm Analysis (cont.) 7 Recursive Algorithm - algorithm that calls itself consists of a sub-problem, which is of exactly the same type as the original problem we attempt to solve the sub-problem and build up a solution to the entire problem RT of Algorithms using Recursion (sub-problem size: n-1) RT(n) = O(1), if n small enough & algorithm terminates RT(n-1) + C condition evaluation and other operations RT of Algorithms using Recursion (sub-problem size: n/a) RT(n) = O(1), if n small enough & algorithm terminates RT(n/a) + C

Algorithm Analysis (cont.) 8 Example [ running time of a recursive algorithm ] fact(n) = n*fact(n-1) = n*(n-1)*fact(n-) = = n*(n-1)*(n-)* *fact(1) = n! public int fact(int n) { if n<=1 return 1; else return n*fact(n-1); }! RT(1) = C (condition evaluation + assignment)! RT() = C + RT(1) = C (condition evaluation + execution of fact(1))! RT(3) = C + RT() = 3C (condition evaluation + execution of fact())!! RT(n) = RT(n-1) + C = C + (n-1)c = nc RT(n) = O(n)

9 Time Complexity of Linear and Binary Search COSC 011, Winter 004, Section N Instructor: N. Vlajic

Linear Search 10 Linear Search - compare each array component in turn with the on Unsorted Array target value, until either of the two occurs: 1) the target value is found ) the end of array is reached static int linearsearch(int target, int[ ] a) { for (int i=0; i<a.length; i++) { if (target == a[i]) return i; } return 1; } O(n) Performance of (1) Best Case RT(n): ~ 1 Linear Search () Worst Case RT(n): ~ n RT(n) = O(n) If an array is not sorted, there is no better algorithm than linear search for finding an element in it.

Linear Search (cont.) 11 Linear Search - by sorting an array, we can improve linear search on Sorted Array operation slightly if current a[i] is greater than target, the search should be terminated immediately static int linearsearch(int target, int[ ] a) { for (int i=0; i<a.length; i++) { if (target == a[i]) return i; if (target < a[i]) return 1; } return 1; } The time complexity of linear search on a sorted array is still O(n), although it requires fewer comparisons than if the array was unsorted.

Binary Search 1 Binary Search algorithm can be used only if the array is sorted (in ascending order). Binary Search - analogous to the way we search through a dictionary 1) compare target with the middle element; if they are not equal, divide the array into sub-arrays ) if target is less (greater) than the middle element, repeat the procedure in the left (right) sub-array 3) repeat the whole procedure until target is found or a sub-array of zero dimension is reached target: 1 3 10 19 3 7 45 53 61 7 99 middle

Binary Search (cont.) 13 Implementation: Iterative Programming static int iterativebinsearch(int target, int[ ] a, int left, int right) { while (left <= right) { } int middle = (left+right) / ; if (target == a[middle]) return middle; else if (target < a[middle]) right = middle 1; else left = middle + 1; } return 1; target: 1 3 10 19 3 7 45 53 61 7 99 left=0 middle right=a.length-1

Binary Search (cont.) 14 Implementation: Recursive Programming static int recursivebinsearch(int target, int[ ] a, int left, int right) { } if (left > right) return 1; int middle = (left+right) / ; if (target == a[middle]) return middle; else if (target < a[middle]) return recursivebinsearch(target,a,left,middle -1); else return recursivebinsearch(target, a, middle+1, rigth); C = O(1) T(n/) In order to find RT, we can employ the recursive formula from pp. 5 (a=).

Complexity of Binary Search on Array of Size n 15 Complexity Analysis ( ( n ) D(n) RT(n) = RT floor + C = O(1) RT(n) = time complexity of binary search on array of size n. D(n) = time complexity of 1) find mid-point, and ) compare mid-point with target,... RT(n) = RT ( n/) + C = RT( n/4) + C = RT( n/8) + 3C =... Let us assume an array of size n= k. Then, in k=log(n) steps n=1 will be reached. RT(n) = RT k-1 k- k-3 ( ) + C = RT( ) + C = RT( ) + 3C =... = RT() 1 + kc RT(n) = O(k) = O(logn)

Sorting Algorithms 16 Time Complexity Algorithm Bubble Sort Insertion Sort Quicksort Mergesort Heapsort Radix Sort Time O(n ) O(n ) O(n ) O(n log(n)) O(n log(n)) O(n) We will take a closer look at some of these algorithms later on...