CS1100 Introduction to Programming

Similar documents
CSCI 104 Sorting Algorithms. Mark Redekopp David Kempe

Programming in Fortran 90 : 2017/2018

Searching & Sorting. Definitions of Search and Sort. Linear Search in C++ Linear Search. Week 11. index to the item, or -1 if not found.

Sequential search. Building Java Programs Chapter 13. Sequential search. Sequential search

Course Introduction. Algorithm 8/31/2017. COSC 320 Advanced Data Structures and Algorithms. COSC 320 Advanced Data Structures and Algorithms

Insertion Sort. Divide and Conquer Sorting. Divide and Conquer. Mergesort. Mergesort Example. Auxiliary Array

Today s Outline. Sorting: The Big Picture. Why Sort? Selection Sort: Idea. Insertion Sort: Idea. Sorting Chapter 7 in Weiss.

Sorting: The Big Picture. The steps of QuickSort. QuickSort Example. QuickSort Example. QuickSort Example. Recursive Quicksort

Sorting Review. Sorting. Comparison Sorting. CSE 680 Prof. Roger Crawfis. Assumptions

Problem Set 3 Solutions

CSE 326: Data Structures Quicksort Comparison Sorting Bound

Sorting. Sorted Original. index. index

CSE 326: Data Structures Quicksort Comparison Sorting Bound

News. Recap: While Loop Example. Reading. Recap: Do Loop Example. Recap: For Loop Example

Sorting. Sorting. Why Sort? Consistent Ordering

Design and Analysis of Algorithms

CS240: Programming in C. Lecture 12: Polymorphic Sorting

Dijkstra s Single Source Algorithm. All-Pairs Shortest Paths. Dynamic Programming Solution. Performance. Decision Sequence.

An Optimal Algorithm for Prufer Codes *

More on Sorting: Quick Sort and Heap Sort

CE 221 Data Structures and Algorithms

Sorting and Algorithm Analysis

Brave New World Pseudocode Reference

ELEC 377 Operating Systems. Week 6 Class 3

CMPS 10 Introduction to Computer Science Lecture Notes

Algorithm To Convert A Decimal To A Fraction

Load Balancing for Hex-Cell Interconnection Network

Kent State University CS 4/ Design and Analysis of Algorithms. Dept. of Math & Computer Science LECT-16. Dynamic Programming

Dijkstra s Single Source Algorithm. All-Pairs Shortest Paths. Dynamic Programming Solution. Performance

Quicksort. Part 1: Understanding Quicksort

Compiler Design. Spring Register Allocation. Sample Exercises and Solutions. Prof. Pedro C. Diniz

Exercises (Part 4) Introduction to R UCLA/CCPR. John Fox, February 2005

Harvard University CS 101 Fall 2005, Shimon Schocken. Assembler. Elements of Computing Systems 1 Assembler (Ch. 6)

Conditional Speculative Decimal Addition*

Esc101 Lecture 1 st April, 2008 Generating Permutation

Assignment # 2. Farrukh Jabeen Algorithms 510 Assignment #2 Due Date: June 15, 2009.

Intro. Iterators. 1. Access

The Greedy Method. Outline and Reading. Change Money Problem. Greedy Algorithms. Applications of the Greedy Strategy. The Greedy Method Technique

Smoothing Spline ANOVA for variable screening

R s s f. m y s. SPH3UW Unit 7.3 Spherical Concave Mirrors Page 1 of 12. Notes

Parallelism for Nested Loops with Non-uniform and Flow Dependences

Assembler. Shimon Schocken. Spring Elements of Computing Systems 1 Assembler (Ch. 6) Compiler. abstract interface.

USING GRAPHING SKILLS

Machine Learning: Algorithms and Applications

Parallel Numerics. 1 Preconditioning & Iterative Solvers (From 2016)

Non-Split Restrained Dominating Set of an Interval Graph Using an Algorithm

CS221: Algorithms and Data Structures. Priority Queues and Heaps. Alan J. Hu (Borrowing slides from Steve Wolfman)

Solving two-person zero-sum game by Matlab

Learning the Kernel Parameters in Kernel Minimum Distance Classifier

9. BASIC programming: Control and Repetition

Virtual Memory. Background. No. 10. Virtual Memory: concept. Logical Memory Space (review) Demand Paging(1) Virtual Memory

Support Vector Machines

CS 534: Computer Vision Model Fitting

A Fast Visual Tracking Algorithm Based on Circle Pixels Matching

3D vector computer graphics

All-Pairs Shortest Paths. Approximate All-Pairs shortest paths Approximate distance oracles Spanners and Emulators. Uri Zwick Tel Aviv University

Overview. CSC 2400: Computer Systems. Pointers in C. Pointers - Variables that hold memory addresses - Using pointers to do call-by-reference in C

NUMERICAL SOLVING OPTIMAL CONTROL PROBLEMS BY THE METHOD OF VARIATIONS

Module Management Tool in Software Development Organizations

Some Advanced SPC Tools 1. Cumulative Sum Control (Cusum) Chart For the data shown in Table 9-1, the x chart can be generated.

ON SOME ENTERTAINING APPLICATIONS OF THE CONCEPT OF SET IN COMPUTER SCIENCE COURSE

Terminal Window. 11. Section 7 Exercises Program Memory Exercise 7-1 Swap Values in an Array Working memory Global Memory. 2 nd call 3 rd call

On Some Entertaining Applications of the Concept of Set in Computer Science Course

Priority queues and heaps Professors Clark F. Olson and Carol Zander

5 The Primal-Dual Method

High level vs Low Level. What is a Computer Program? What does gcc do for you? Program = Instructions + Data. Basic Computer Organization

Lecture 5: Multilayer Perceptrons

A Binarization Algorithm specialized on Document Images and Photos

6.854 Advanced Algorithms Petar Maymounkov Problem Set 11 (November 23, 2005) With: Benjamin Rossman, Oren Weimann, and Pouya Kheradpour

Life Tables (Times) Summary. Sample StatFolio: lifetable times.sgp

Computer models of motion: Iterative calculations

Classifier Selection Based on Data Complexity Measures *

CHAPTER 10: ALGORITHM DESIGN TECHNIQUES

Assembler. Building a Modern Computer From First Principles.

Cluster Analysis of Electrical Behavior

2x x l. Module 3: Element Properties Lecture 4: Lagrange and Serendipity Elements

Line Clipping by Convex and Nonconvex Polyhedra in E 3

The stream cipher MICKEY-128 (version 1) Algorithm specification issue 1.0

Report on On-line Graph Coloring

X- Chart Using ANOM Approach

Content Based Image Retrieval Using 2-D Discrete Wavelet with Texture Feature with Different Classifiers

Hermite Splines in Lie Groups as Products of Geodesics

Circuit Analysis I (ENGR 2405) Chapter 3 Method of Analysis Nodal(KCL) and Mesh(KVL)

Introduction to Programming. Lecture 13: Container data structures. Container data structures. Topics for this lecture. A basic issue with containers

Hierarchical clustering for gene expression data analysis

Fast Computation of Shortest Path for Visiting Segments in the Plane

Array transposition in CUDA shared memory

Introduction to Geometrical Optics - a 2D ray tracing Excel model for spherical mirrors - Part 2

An Application of the Dulmage-Mendelsohn Decomposition to Sparse Null Space Bases of Full Row Rank Matrices

The Shortest Path of Touring Lines given in the Plane

Greedy Technique - Definition

Vectorization in the Polyhedral Model

Parallel matrix-vector multiplication

Performance Evaluation of Information Retrieval Systems

Quality Improvement Algorithm for Tetrahedral Mesh Based on Optimal Delaunay Triangulation

Polyhedral Compilation Foundations

SLAM Summer School 2006 Practical 2: SLAM using Monocular Vision

Q.1 Q.20 Carry One Mark Each. is differentiable for all real values of x

Loop Transformations, Dependences, and Parallelization

Machine Learning 9. week

Transcription:

Factoral (n) Recursve Program fact(n) = n*fact(n-) CS00 Introducton to Programmng Recurson and Sortng Madhu Mutyam Department of Computer Scence and Engneerng Indan Insttute of Technology Madras nt fact (nt n) f (n == ) return ; return n*fact(n-); Shorter, smpler to understand Uses fewer varables Machne has to do more work runnng ths one! Course Materal SD, SB, PSK, NSN, DK, TAG CS&E, IIT M Tree Recurson When the recursve call s made more than once nsde the functon. For example, Fbonacc numbers fb(n) = fb(n-) + fb(n-) f n > = n f n s 0 or Ackerman s functon One of the fastest growng functons A(m, n) = n + f m = 0 = A(m-, ) f n = 0 = A(m-, A(m, n-)) otherwse 3 Fbonacc Numbers fb(4) fb(5) fb(3) fb(3) fb() fb() fb() 0 0 fb() fb() fb() fb(0) fb() fb(0) fb() 0 fb(0) 3 5 nt fb(nt n) /* n >= 0 */ f (n == 0) return 0; f (n == ) return ; return fb(n - ) + fb(n - ); 4 Fbonacc Numbers Lnear Recurson nt fb(nt n) return fb_aux( n,, 0) nt fb_aux(nt n, nt next, nt result) f (n == 0) return result; return fb_aux(n -, next + result, next); Computaton beng done n the recursve call f: 0,,,, 3, 5, 8 n: 0,,, 3, 4, 5, 6 fb(5) fb_aux(5,, 0) fb_aux(4,, ) fb_aux(3,, ) fb_aux(, 3, ) fb_aux(, 5, 3) fb_aux(0, 8, 5) 5 Who Was Fbonacc? The "greatest European mathematcan of the mddle ages" Hs full name was Leonardo of Psa Born n Psa (Italy), about 75 AD Was one of the frst people to ntroduce the Hndu-Arabc number system nto Europe These are the nne fgures of the Indans: 9 8 7 6 5 4 3. Wth these nne fgures, and wth ths sgn 0 whch n Arabc s called zephrum, any number can be wrtten. Part of hs book Lber abac Best known for a smple seres of numbers, later named the Fbonacc numbers n hs honour. 6

Fbonacc Numbers The seres begns wth 0 and. After that, use the smple rule: Add the last two numbers to get the next,, 3, 5, 8, 3,, 34, 55, 89, 44, 33, 377, 60, 987,... Suppose a newly-born par of rabbts, one male, one female, are put n a feld. Rabbts are able to mate at the age of one month so that at the end of ts second month a female can produce another par of rabbts. Suppose that our rabbts never de and that the female always produces one new par (one male, one female) every month from the second month on. The puzzle that Fbonacc posed was... How many pars wll there be n one year? Rabbt Pars How many pars wll there be n one year?. At the end of the frst month, they mate, but there s stll one only par.. At the end of the second month the female produces a new par, so now there are pars of rabbts n the feld. 3. At the end of the thrd month, the orgnal female produces a second par, makng 3 pars n all n the feld. 4. At the end of the fourth month, the orgnal female has produced yet another new par, the female born two months ago produces her frst par also, makng 5 pars. In general, magne that there are x n pars of rabbts after n months. The number of pars n month n+ wll be x n (n ths problem, rabbts never de) plus the number of new pars born. But new pars are only born to pars at least month old, so there wll be x n- new pars. x n+ = x n + x n- 7 8 Rabbt Pars An Erratc Sequence In Godel, Escher, Bach: An Eternal Golden Brad, D. R. Hofstadter ntroduces several recurrences whch gve rse to partcularly ntrgung nteger sequences. Hofstadter's Q sequence (also known as Meta-Fbonacc sequence) Q() = Q() = Q(n) = Q(n - Q(n - )) + Q(n - Q(n - )) for n > Each term of the sequence s the sum of two precedng terms, but (n contrast to the Fbonacc sequence) not necessarly the two last terms. The sequence Q(n) shows an erratc behavour,,, 3, 4, 5, 5, 6, 6, 6, 8, 8, 8, 0, 9, 0, gets more and more erratc 9 0 Whch s the Bggest? Gven three numbers a, b, and c, fnd the bggest amongst them. Defne a varable max to store the value. f (a > b && a > c) max = a; else f (b > c) max = b; else max = c; Other smlar code also works Method works for array elements as well A(), A(), A(3) But what f the array s large? Ths approach s not feasble Hghest Marks Gven an array marks[00], fnd the hghest marks n the class. max = marks[0]; /* for the tme beng */ for (=; <00; ++) f (marks[] > max) max = marks[]; /* update f bgger */

More Statstcs Gven an array marks[00], fnd the hghest, lowest and average marks n the class. max = marks[0]; /* for the tme beng */ mn = marks[0]; sum = marks[0]; for (=; <00; ++) f (marks[] > max) max = marks[]; f (marks[] < mn) mn = marks[]; sum += marks[]; average = sum/00; /*assumng floatng pont*/ 3 Exchangng Values Exchange the values of varables (a and b) a = b; INCORRECT b = a; Value of a s lost! Need to use a temporary varable temp = a; /* save the value of a */ a = b; b = temp; 4 Exchangng Values wthout temp What about the followng method that does not use an extra varable? a = a+b; b = a - b; a = a - b; Exercse: Does t work? What are the lmtatons? Do you need to be careful about somethng? Swap Array Elements vod swap (nt array[ ], nt, nt j) nt temp; temp = array[]; array[] = array[j]; array[j] = temp; 5 6 Where s the Hghest Number? Gven an array of n elements, a startng ndex, fnd out where the largest element les beyond and ncludng. nt MaxIndex (nt array[ ], nt start, nt arraysze) nt = start; nt ndex = start; nt max = array[]; for ( ; < arraysze; ++) /* observe null statement */ f (array[] > max) max = array[]; ndex = ; return ndex; 7 Sortng an Array of Numbers Problem: Arrange the marks n decreasng order startng wth the maxmum. One approach Fnd the maxmum value n marks[0] marks[99] Remember the ndex where t occurred Exchange (values of) marks[0] and marks[] Fnd the maxmum value n marks[] to marks[99] exchange marks[] and marks[]... do ths tll marks[98] 8 3

Selecton Sort for (=0, <= n -, ++) swap (marks,, MaxIndex(marks,, n)); or more legbly swap s an functon that passes array by reference. The last element need not be tested for (=0, <= n -, ++) nt maxindex = MaxIndex(marks,, n); f (maxindex!= ) swap(marks,, maxindex); Selecton Sort as a Functon vod selectsort(nt array[ ], nt sze) nt maxindex, ; for ( = 0; <= sze ; ++) maxindex = MaxIndex(array,, sze) f (maxindex!= ) swap(array,, maxindex); 9 0 An Example 0 3 4 5 6 7 7 5 8 3 6 4 0 maxindex 4 8 7 5 3 6 4 8 7 5 3 6 4 6 8 7 6 5 3 4 3 3 8 7 6 5 3 4 4 7 8 7 6 5 4 3 5 5 Complexty of Selecton Sort 0 3 4 5 6 7 8 9 n=0 =0 n-=9 comparsons = n-=8 comparsons = n-3=7 comparsons =3 n-4=6 comparsons =4 n-5=5 comparsons =5 n-6=4 comparsons =6 n-7=3 comparsons =7 n-8= comparsons =8 n-9= comparson (n-)*n n / Complexty of Selecton Sort In each teraton, MaxIndex fnds the maxmum element Complexty of MaxIndex s order n à O(n) Can we do ths faster? Yes, by arrangng the numbers n a data structure called a MaxHeap MaxHeap can extract max element n O(log(n)) Algorthm Heapsort complexty O(n log(n)) Selecton sort does (n-) passes of reducng length (average length n/) Complexty (n-)*n/ à O(n /) à O(n ) Inserton Sort Inserton sort also scans the array from left to rght When t looks at the th element, t has elements up tll (-) sorted sorted It moves the th element to ts correct place by shftng the smaller elements to the rght 3 4 4

InsertMax Functon sorted Complexty of InsertMax sorted vod InsertMax (nt array[ ], nt ndex) nt = ndex; nt valueatindex = array[ndex]; whle( > 0 && array[-] < valueatindex) array[] = array[-]; /*shft rght*/ --; array[] = valueatindex; If the th element s n sorted order (smaller than the sorted set), no shft s done The maxmum number of shfts s (-) Complexty worst case O() best case O() constant tme 5 6 Inserton Sort Functon vod InsertonSort(nt array[ ], nt sze) nt ; for( = ; <= sze ; ++) InsertMax(array[ ], ); Complexty best case O(n) worst case O(n /) = O(n ) An Example 0 3 4 5 6 7 7 5 8 3 6 4 # of comp 7 5 8 3 6 4 7 5 8 3 6 4 3 3 7 5 8 3 6 4 4 4 8 7 5 3 6 4 5 3 7 8 7 5 3 6 4 6 5 8 Selecton Vs Inserton Sort Scannng from left to rght Selecton sort Swaps the th element wth the largest unsorted element Inserton sort Inserts the th element nto ts proper place 9 Selecton Vs Inserton Selecton sort always does the same number of computatons rrespectve of the nput array Inserton sort does less work f the elements are partally sorted when the th element s n place, t does not have to shft any elements constant tme If the nput s already sorted, Inserton sort merely scans the array left to rght confrmng that t s sorted On the average, Inserton sort performs better than Selecton sort 30 5

Inserton Sort Sorted Input Inserton Sort Reverse Sorted Input The best case complexty of InsertMax s O(). In each pass, functon InsertMax makes one comparson. Area n (n- lnes of unt length per area) The worst case complexty of InsertMax s O(n). In each pass, functon InsertMax has to move the element to the leftmost poston. Area n (n- lnes of average length per area as n/) 3 3 Inserton Sort Random Input The worst case complexty of Inserton sort s O(n ). In each pass, functon InsertMax has to move the element to the leftmost poston. Area < n / Exercse for ths Week Gven an array of strngs, called names, and an array of marks, called marks, such that marks[] contans the marks of names[] sort the two lsts n decreasng order of marks sort the two lsts n alphabetc order of names fgure out how to compare two names to decde whch comes frst. 33 34 6