350 likes | 856 Views
Advanced Data Structures and Algorithms. COSC-600 Lecture notes presentation-3. Running Time Calculations. There are several ways to estimate the running time of a Program. There are many algorithms but to eliminate bad ones some analysis is required.
E N D
Advanced Data Structures and Algorithms COSC-600 Lecture notes presentation-3
Running Time Calculations There are several ways to estimate the running time of a Program. There are many algorithms but to eliminate bad ones some analysis is required. To simplify the analysis we do computing a Big-Oh running time of the program. The presentation is followed by some sample examples and some general rules in calculating running time.
For loops the running time of the statements inside the loop times the number of iterations. • In Nested loops the total running time of a statement inside a group of nested loops is the running time of the statement multiplied by the product of sizes of all loops. for( i = 0; i < n; i++ ) for( j = 0; j < n; j++ ) k++; The above program fragment is O(N^2).
Consecutive statements: As an example, the following programming fragment, which has O(N) work followed by O(N^2) work , is also O(N^2). for( i = 0; i < n; i++ ) {a[ i ] = 0; for( i = 0; i < n; i++ ) {for( j = 0; j < n; j++ ) a[ i ] += a[ j ] + i + j; }}
If/else running time is never more than that of the test plus the larger of the running times of S1 and S2. • Without recursion: public static long factorial( int n ) {if( n <= 1 ) return 1; else return n * factorial( n - 1 ); }
Using recursion: public static long fib( int n ) { if( n <= 1 ) return 1; else return fib( n - 1 ) + fib( n - 2 );} We have the formula for the running time of fib(n): T(N) = T(N − 1) + T(N − 2) + 2
Maximum Subsequence Sum Problem • We can present this algorithm to solve the Maximum subsequence sum problem in four ways. They are: a) Cubic maximum contiguous subsequence sum algorithm, b) Quadratic maximum contiguous subsequence sum algorithm, c) Recursive maximum contiguous subsequence sum algorithm,
d) Linear-time maximum contiguous subsequence sum algorithm. Please refer page 39 for the complete computation and comparison of the different methods in calculating running time and the time complexity of each and every method.
Binary Search • It is a search Algorithm used to finf some ‘n’ data in a group of data. • Thus to calculate the maximum we need to scan the array once in the order being O(n). • Now, if the array is sorted in some order, then we just compare the value to be found with center object of the array. • In this comparison we keep eliminating half of the array every step , leaving the order to be O(log n).
If suppose we have a two dimensional array, We would scan each row and coloumn in the order to be n*n = O(n^2). • The actual order is nlog(n).If the two dimensional array is sorted, it can still be reduced to O(n) by using zig-zag pattern to scan. • The worst case we will end up scanning (2n-1) = O(n).