Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)

Slides:



Advertisements
Similar presentations
Lecture 22: Arrays (cont). 2 Lecture Contents: t Searching in array: –linear search –binary search t Multidimensional arrays t Demo programs t Exercises.
Advertisements

Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Chapter 1 – Basic Concepts
the fourth iteration of this loop is shown here
Chapter 2: Algorithm Analysis
Lecture 2 Feb 3, 2009 goals: continue recursion more examples of recursive programs.
Lecture 3 Sept 3, 2010 Goals: Chapter 2 (algorithm analysis) Examples: Selection sorting rules for algorithm analysis Image representation Image processing.
Lecture 2 Aug goals: Introduction to recursion examples of recursive programs.
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
Lecture 2 Aug 28 goals: Introduction to recursion examples of recursive programs.
Simple Sorting Algorithms
Lecture 5 Sept 9 Goals: Selection sorting Insertion sorting (completion) 2-d arrays Image representation Image processing examples.
Lecture 12 Oct 13, 2008 Some simple recursive programs recursive problem solving, connection to induction Some examples involving recursion Announcements.
Algorithm Design Techniques: Induction Chapter 5 (Except Section 5.6)
Lecture 5 Sept 12, 2011 Goals: Linked list (Chapter 3) list class in STL (section 3.3) implementing with linked lists.
Lecture 4 Feb 5 completion of recursion (inserting into a linked list as last item) analysis of algorithms – Chapter 2.
Lecture 3 Aug 31, 2011 Goals: Chapter 2 (algorithm analysis) Examples: Selection sorting rules for algorithm analysis discussion of lab – permutation generation.
Algorithm Analysis CS 201 Fundamental Structures of Computer Science.
Lec 5 Feb 10 Goals: analysis of algorithms (continued) O notation summation formulas maximum subsequence sum problem (Chapter 2) three algorithms image.
Algorithm Efficiency and Sorting
Data Structure Algorithm Analysis TA: Abbas Sarraf
C++ for Engineers and Scientists Third Edition
Analysis of Algorithm.
Copyright © Cengage Learning. All rights reserved. CHAPTER 11 ANALYSIS OF ALGORITHM EFFICIENCY ANALYSIS OF ALGORITHM EFFICIENCY.
Lecture 3 Feb 7, 2011 Goals: Chapter 2 (algorithm analysis) Examples: Selection sorting rules for algorithm analysis Image representation Image processing.
Lecture 5 Feb 14, 2011 Goals: Linked list (Chapter 3) list class in STL (section 3.3) implementing with linked lists.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Algorithm Analysis Dr. Bernard Chen Ph.D. University of Central Arkansas.
Chapter 6 Algorithm Analysis Bernard Chen Spring 2006.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 2.6 Comparison of Algorithms modified from Clifford A. Shaffer and George Bebis.
C. – C. Yao Data Structure. C. – C. Yao Chap 1 Basic Concepts.
Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 10 Scott Marino.
1 Sorting Algorithms (Basic) Search Algorithms BinaryInterpolation Big-O Notation Complexity Sorting, Searching, Recursion Intro to Algorithms Selection.
Introduction to complexity. 2 Analysis of Algorithms Why do we need to analyze algorithms? –To measure the performance –Comparison of different algorithms.
Vishnu Kotrajaras, PhD.1 Data Structures. Vishnu Kotrajaras, PhD.2 Introduction Why study data structure?  Can understand more code.  Can choose a correct.
Data Structures and Algorithms Lecture 5 and 6 Instructor: Quratulain Date: 15 th and 18 th September, 2009 Faculty of Computer Science, IBA.
Algorithm Analysis. Algorithm An algorithm is a clearly specified set of instructions which, when followed, solves a problem. recipes directions for putting.
CS 1704 Introduction to Data Structures and Software Engineering.
Analysis of Algorithms
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
Analysis of Algorithms These slides are a modified version of the slides used by Prof. Eltabakh in his offering of CS2223 in D term 2013.
Algorithms and Algorithm Analysis The “fun” stuff.
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
CSS342: Algorithm Analysis1 Professor: Munehiro Fukuda.
CSC 211 Data Structures Lecture 13
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Lecture 2 Jan Goals: Introduction to recursion Examples of recursive programs Reading: Chapter 1 of the text.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Data Structure Introduction.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
Algorithm Analysis Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
Lecture 6 Feb 8, 2012 Goals: Linked list (Chapter 3) list class in STL (section 3.3) implementing with linked lists.
Algorithm Analysis Chapter 5. Algorithm An algorithm is a clearly specified set of instructions which, when followed, solves a problem. –recipes –directions.
CISC 235: Topic 1 Complexity of Iterative Algorithms.
Algorithm Analysis. What is an algorithm ? A clearly specifiable set of instructions –to solve a problem Given a problem –decide that the algorithm is.
CSC 143Q 1 CSC 143 Program Efficiency [Chapter 9, pp ]
Vishnu Kotrajaras, PhD.1 Data Structures
1 Chapter 2 Algorithm Analysis All sections. 2 Complexity Analysis Measures efficiency (time and memory) of algorithms and programs –Can be used for the.
1 Chapter 2 Algorithm Analysis Reading: Chapter 2.
Building Java Programs Chapter 13 Lecture 13-1: binary search and complexity reading:
Chapter 2 Algorithm Analysis
Analysis of Algorithms
Chapter 9: Searching, Sorting, and Algorithm Analysis
Algorithm Analysis CSE 2011 Winter September 2018.
Programming and Data Structure
Searching and Sorting 1-D Arrays
Programming and Data Structure
Presentation transcript:

Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)

Parameter passing call by value and reference: What are the outputs of the following program? #include using namespace std; int f(int x) { x++; cout << x << endl; return x*x; } int main() { int x = 5; cout << f(x) << endl; cout << x << endl; } #include using namespace std; int f(int& x) { x++; cout << x << endl; return x*x; } int main() { int x = 5; cout << f(x) << endl; cout << x << endl; }

Parameter passing In c++, all parameter passing is done by value unless & is used preceding the name of the variable. Advantage of call by value: safer easier to understand and debug Disadvantage of call by value: not efficient (copying costs both in time and space) especially a problem when a large object is passed as parameter. call by reference is complementary

Parameter passing call by const reference: getting advantages of both conventions should be used when passing objects (especially when it is large) call by const reference: getting advantages of both conventions should be used when passing objects (especially when it is large) Constant return value from a function (The returned object can’t be modified.) Section 1.6 templates

Implementation of a list class list class with the following functionality: list is singly-linked, with a head pointer constructor(s) functions: insert(int item, int posn) length() delete(int posn) search(int item)

Implementing insert To insert a key x as the k-th key a k g c x = ‘b’ and k = 5 a k g c b

Recursive version of insert void insert(int x, int k) { // insert x as the k-th item of the list // assume that the list has at least k – 1 items Node* tmp = new Node(k); if (k == 1) { tmp->next = head; head = tmp; } else { List temp(head->next); temp.insert(x, k – 1); }

Insertion sorting At the start of the k-th cycle: A[0.. k–1] is sorted. At the end of the k-th cycle: A[k] is inserted into correct place so that A[0.. k] is sorted. Example: k = 5 Before: After:

Insertion step temp = A[j]; for (k = j – 1; k >= 0 && A[k] > temp; --k) A[k+1] = A[k]; A[k+1] = temp;

Insertion sorting Repeat the insertion cycle for j = 1, 2, 3, …, n – 1. The complete code is as follows: for (j = 1; j < n; ++j) { temp = A[j]; for (k = j – 1; k >= 0 && A[k] > temp; --k) A[k+1] = A[k]; A[k+1] = temp; }

The following link contains an applet to animate various sorting (and other) algorithms: A screen shot is shown below:

Selection Sort Selection Sorting Algorithm: During the j-th pass (j = 0, 1, …, n – 2), we will examine the elements of the array a[j], a[j+1], …, a[n- 1] and determine the index min of the smallest key. Swap a[min] and a[j]. Re selection_sort(vector a) { if (a.size() == 1) return; for (int j = 0; j < n – 1; ++j) { min = j; for (int k= j+1; k<=n-1; ++k) if (a[k] < a[min]) min = k; swap a[min] and a[j]; } Selection sorting animation can be found in the same site.

Algorithm analysis Analysis is the process of estimating the number of computational steps performed by a program (usually as a function of the input size). Useful to compare different approaches. Can be done before coding. Does not require a computer (paper and pencil). Order of magnitude (rough) estimate is often enough. We will introduce a notation to convey the estimates. (O notation).

Insertion sorting - analysis for (j = 1; j < n; ++j) { temp = A[j]; for (k = j – 1; k >= 0 && A[k] > temp; --k) A[k+1] = A[k]; A[k+1] = temp; } How many comparisons are performed? Consider the j-th iteration of the inner loop. In the worst-case, the loop will be iterated j times. Each time, two comparisons are performed. Total = 2j

First iteration performs 2 x 1 comparisons Second iteration performs 2 x 2 comparisons.... n – 1 th iteration performs 2 x (n – 1) comparisons Total number of comparisons performed by insertion sorting = 2 x ( … + n – 1) = n (n – 1) ~ n 2 comparisons Note the approximation we used: When n = 1000, n 2 = one million, n 2 – n = so the error in our estimate is 0.1%

Analysis of selection sorting Consider the program to find the min number in an array: min = a[0]; for (j = 1; j < n; ++j) if (A[j] > min) min = A[j]; The number of comparisons performed is n – 1. loop starts with j = 1 and ends with j = n so the number of iterations = n – 1. In each iteration, one comparison is performed.

Selection sorting – analysis The inner loop: n – 1 comparisons during the first iteration of the inner loop n – 2 comparisons during the 2nd iteration of the inner loop comparison during the last iteration of the inner loop Total number of comparisons = … + (n – 1) = n(n – 1)/ 2

General rule If there is a nested loop, analyze the inner loop and calculate the number of operations performed by the inner loop. Suppose the j-th iteration of the inner loop performs f(j) operations Suppose the value of j in the outer loop goes from 1 to m, then the total number of operations is f(1) + f(2) + … + f(m)

Exercise: What is the number of operations (additions) by the following program? for (j = 100; j < 200; ++j) if (j % 2 == 0) sum+= A[j];

Exercise: What is the number of operations (additions) by the following program? for (j = 100; j < 200; ++j) if (j % 2 == 0) sum+= A[j]; Answer: The number of iterations of the loop = 100, But the addition is performed in every other iteration so the number of additions performed = 50.

O (order) notation Definition: Let f(n) and g(n) be two functions defined on the set of integers. If there is a c > 0 such that f(n) <= c g(n) for all large enough n. Then, we say f(n) = O(g(n)). Example: n 2 + 2n – 15 is O(n 2 ) Rule: When the expression involves a sum, keep only the term with the highest power, drop the rest. You can also drop constant multiplying terms. (3n n + 1) (4 n – 5) is O(n 3 )

Max Subsequence Problem w Given a sequence of integers A1, A2, …, An, find the maximum possible value of a subsequence Ai, …, Aj. w Numbers can be negative. w You want a contiguous chunk with largest sum. w Example: -2, 11, -4, 13, -5, -2 w The answer is 20 (subsequence A2 through A4). w We will discuss three different algorithms, with time complexities O(n 3 ), O(n 2 ), and O(n). w With n = 10 6, algorithm 1 may take > 10 years; algorithm 3 will take a fraction of a second!

int maxSum = 0; for( int i = 0; i < a.size( ); i++ ) for( int j = i; j < a.size( ); j++ ) { int thisSum = 0; for( int k = i; k <= j; k++ ) thisSum += a[ k ]; if( thisSum > maxSum ) maxSum = thisSum; } return maxSum; Algorithm 1 for Max Subsequence Sum w Given A 1,…,A n, find the maximum value of A i +A i+1 +···+A j 0 if the max value is negative n Time complexity: O(n 3 )

Algorithm 2 w Idea: Given sum from i to j-1, we can compute the sum from i to j in constant time. w This eliminates one nested loop, and reduces the running time to O(n 2 ). into maxSum = 0; for( int i = 0; i < a.size( ); i++ ) int thisSum = 0; for( int j = i; j < a.size( ); j++ ) { thisSum += a[ j ]; if( thisSum > maxSum ) maxSum = thisSum; } return maxSum;

25 Algorithm 3 int maxSum = 0, thisSum = 0; for( int j = 0; j < a.size( ); j++ ) { thisSum += a[ j ]; if ( thisSum > maxSum ) maxSum = thisSum; else if ( thisSum < 0 ) thisSum = 0; } return maxSum n The algorithm resets whenever prefix is < 0. Otherwise, it forms new sums and updates maxSum in one pass.