Docsity

Computer Science I - Study Guide for Exam | COP 3502, Exams of Computer Science

Toggle sidebar
bg1
Software development
• Understand and define the problem
– what is it that needs to be solved
• Identify an approach
– the basic equations, relations, etc
• Develop and specify an algorithm
• Sequence of steps to be executed
• Specify how data is organized .
• Evaluate the algorithm
– always provide correct results ?
is it efficient?
• Coding
• Develop functions for input/output or processing the data
• Test and validate
• Debug program
Run various test cases
• confirm -- gives expected results?
• confirm efficiency .
• Documentation
– Problem statement,
– solution process ,
– algorithm,
– program code
– testing procedure
• Program maintenance
• Make necessary changes if errors are found
• Ensure that it meets user changing requirements
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download Computer Science I - Study Guide for Exam | COP 3502 and more Exams Computer Science in PDF only on Docsity!

Software development

  • Understand and define the problem
    • what is it that needs to be solved
  • Identify an approach
    • the basic equations, relations, etc
  • Develop and specify an algorithm
    • Sequence of steps to be executed
    • Specify how data is organized .
  • Evaluate the algorithm
    • always provide correct results? is it efficient?
  • Coding
    • Develop functions for input/output or processing the data
    • Test and validate
      • Debug program Run various test cases
      • confirm -- gives expected results?
      • confirm efficiency .
  • Documentation
    • Problem statement,
    • solution process ,
    • algorithm,
    • program code
    • testing procedure
  • Program maintenance
    • Make necessary changes if errors are found
    • Ensure that it meets user changing requirements

Algorithms for problem solving

ALGORITHMS

An algorithm is a detailed sequence of actions to perform to accomplish some task. The name comes from an Iranian mathematician Al-Khawarizmi.

Other definitions:

  • A finite set of step-by-step instructions for a problem-solving or computation procedure, especially one that can be implemented by a computer.
  • A mathematical procedure that can usually be explicitly encoded in a set of computer language instructions that manipulate data.
  • An ordered sequence of well defined and effective operations which, when executed, will terminate in finite amount of time and produce correct result.

However, the steps of an algorithm are not dependent on any specific computer language. It gives an idea of the logical steps used, without bothering about the syntax of a language. It helps us in checking if the solution process is correct and efficient, even before it is run on a computer. An algorithm can be coded in any computer language.

Properties of good algorithms :

Precision:

  • Each step must be clear and unambiguous.
  • each step must be finite
  • Number of steps must be finite

Simplicity:

  • Each step must be simple enough to be easily understood
  • Should translate to a few lines of code

Levels of Abstraction:

-steps should be grouped into related modules -other algorithms are called by names instead of complete code -details should be hidden at higher levels of abstraction You might say that the algorithm can be described through a “pseudo code“. Here are some examples of algorithms.

Algorithm C

  1. If number is even, smallest divisor =2, Go to step 8.
  2. If number is divisible by 3, smallest divisor = 3, Go to step 8.
  3. Let divisor be 3.
  4. Find factor = number/divisor (get nearest integer value)
  5. remainder = number mod 3 6 As long as remainder is not zero & divisor < factor keep on doing the following: 6a. divisor = divisor +2. 6b. remainder = number mod divisor. 6c. factor = number / divisor
  6. if number mod divisor is zero, smallest divisor = divisor Else, smallest divisor = 1.
  7. print smallest divisor.

Compare the number of operations involved in each of the algorithms.

Finding largest sequence of Ones

Consider a two dimensional array. Each row consists of sequence of Ones, followed by sequence of Zeros. The problem is to find the maximum number of Ones in any row.

111111000000000000000000 111111111111100000000000 111110000000000000000000 111111111111111111111000 111100000000000000000000 111111111111110000000000 110000000000000000000000

Algorithm 1:

Let any element of this 2 dimensional array of rows x cols be a(j,k)

max = 0; for j = 1 to rows { find total number of Ones; if total >max set max = total; }

How many operations involved? = cols x rows

Algorithm 2:

Find the position of last 1 in first row. Start examining second row from that position onward. Get the position of last 1. Start next row from that position. If that position contains zero, skip that row. Keep a record of row where change was made. Stop when all rows examined.

How many operations now? ( number of cols+ no. of rows ).

Measuring Time Complexity

Counting number of operations involved in the algorithms to handle n items. Meaningful comparison possible for very large values of n.

Algorithm Analysis: Loops

LOOP 1:

a= 0; b = 0; for (k=0; k< n; k++) { for (j = 0; j < m; j++) a= a + j; }

It takes nm addition operations.

LOOP 2:

a= 0; b = 0; for (k=0; k< n; k++) { a= a+k; ……(1) for (j = 0; j < m; j++) b= b + j; ……(2) }

It takes nm+ n addition operations.

LOOP 3:

total = 0; for (k=0; k<n; ++k) { rows[k] = 0; for (j = 0; j <n; ++j){ rows[k] = rows[k] + matrix[k][j];……(3) total = total + matrix[k][j]; ……(4) } }

It takes 2n^2 addition operations

LOOP 4:

total =0; for (k=0; k<n; ++k) rows[k] = 0; for (j = 0; j <n; ++j) rows[k] = rows[k] +matrix[k][j];……(5) total = total + rows[k]; ………(6) }

This one takes n^2 + n operations.

Complexity of testing elements of an array

Let ar[ ] be an array containing n integer values. It is desired to find the number of elements having value more than 50. sum = 0; for(k = 0; k<n; k++) if(ar[k]>50) sum+ = ar[k];

for each value one comparison is carried out, and the assignment statement may get executed only for some of the values.

Worst case : All values are more than 50, (all values are checked and total gets incremented every time). no. of operations = 2n

Best case : When all values are less than 50. (all values are checked and none gets incremented number of operations = n

Complexity of a sorting algorithm:

Selection Sort

A sorting process consists of reordering the elements in an array so that they are arranged in an increasing or decreasing sequence. One simple sorting method is known as the Selection sort. To sort the elements in ascending order (smallest to largest), it examines each element in the list, finds the smallest element and swaps it with the first element in the array. Then it examines the array starting with the second element, finds the smallest element and swaps it with the second element. The steps are repeated till it has swapped the last element in place.

56 25 37 58 95 19 73 30

Sorted array after pass 1: 19 25 37 58 95 56 73 30

Algorithm for selection sort:

**1. for lh taking on values 0 to n-1 do steps 2-5.

  1. set rh = lh as starting value of the new array.
  2. Examine all elements of new array with index j by** **doing step 4.
  3. If the element at j < element at rh, then set** **rh=j.(Find the smallest element).
  4. swap element at index lh with element at rh.(smallest** element stored in beginning of new array)

Implementation:

void selectionsort(int array[],int n) { int lh, rh, j, temp; for(lh=0; lh<n; lh++) { rh = lh; for(j=lh+1; j<n; j++) if(array[j]<array[rh]) rh = j;

temp = array[lh]; array[lh]=array[rh]; array[rh]=temp; } }

Analyzing performance of selection sort

In the first cycle, the inner loop examines n elements, so it takes n operations. During the next cycle it examines n – 1 elements, then n – 2 elements and so on till it examines only one element in the end. Thus total number of operations T is given by the expression

T = n + n – 1 + n – 2 + ……+ 3 + 2 + 1

= Σ j

= n (n + 1 ) / 2

= (n 2 + n)/ 2

Is this term proportional to n or n^2? Study the following table

n T

10 55 100 5, 400 80, 1000 500,

It is obvious that T is more nearer to n^2 than n. Thus we can say that the selection sort algorithm is of order n^2.

Similarly for any algorithm we can work out a complicated expression for T, but we want a simpler qualitative answer, so that we can compare performance of two algorithms.

Let f(n) = 2 n^2 + 3 n + 1

Let us assume f(n) = O (n 2 )

So as per definition of Big-O, we must have

f(n) < = c g(n)

or 2 n^2 + 3 n + 1 < = c n^2

To determine range of values for c, we divide both sides by n^2

2 + (3/n) + ( 1 / n 2 ) < = c

You want to find c such that a term in f becomes the largest and stays the largest. Compare first and second term.

First will overtake the second at n = 2, so for n= 2, c >= 3.75,

for n = 5, c >= slightly more than 2,

for very large values of n, c is almost 2.

g is almost always > = f if it is multiplied by a constant c

Look at it another way : suppose you want to find weight of elephants, cats and ants in a jungle. Now irrespective of how many of each item was there, the net weight would be proportional to the weight of an elephant.

So here the first term 2 n 2 dominates the other terms, which can be neglected in comparison with the first term, and we can say

f(n) = O(2 n^2 )

The constant term has no significance, and the complexity can be finally expressed as

f(n) = O (n^2 )

Incidentally we can also say f is big -O not only of n^2 but also of n 3 , n^4 , n^5 etc (HOW ?)

The complexity of an expression

O (3n 4 + 35n^2 + 100)

is evaluated by first dropping the insignificant terms, to yield

O( 3n^4 )

and then dropping the constant factor to get

O( n^4 )

Complexity of the Linear search Algorithm in terms of Big O:

Best Case - It’s the first value : “order 1,” O(1) Worst Case - It’s the last value, n: “order n,” O(n) Average - N/2 (if value is present): “order n,” O(n)

Example 2:

Use big-O notation to analyze the time complexity of the following fragment of C code:

for (k=1; k<=n/2; k++) { sum = sum + 5;

} for (j = 1; j <= nn; j++) { delta = delta +1; . }*

The number of operations executed by these loops is the sum of the individual loop operations.

The complexity of total operations n/2+n^2 would be O( n^2 ) in big-O terms.

Thus, for two loops with O[ f 1 (n) ] and O[ f 2 (n) ] complexities, the overall complexity of sequencing the two loops is O[ f (^) D(n) ] where f (^) D(n) is the dominant term corresponding to the functions f 1 (n) and f 2 (n).

Plot of f and g, in range 0 to 100 Plot of f and g, in range 0 to 1000

In the first graph, drawn for very limited values of n, the curves appear somewhat different. In the second graph, they sort of start moving somewhat similar, in the third graph for appreciable values of n, there is only a very small difference between f(n) and g(n), and in the last graph drawn for very large values of n, the plots are virtually identical. In fact, they approach n 3 , the dominant term. As n gets larger, the other terms become minuscule in comparison to n^3.

As you can see, improving an algorithm's non-dominant terms doesn't help much. What really matters is the dominant term. This is why we adopt the big-O notation for this. We say that:

f ( n ) = n^3 - 12 n^2 + 20 n + 110

= O ( n^3 )

Or in other words, f(n) is of order n^3.

Order notations used in computer science

O(1) or “Order One”: Constant time

  • does not mean that it takes only one operation
  • does mean that the work doesn’t change as n changes
  • is a notation for “constant work”

O(n) or “Order n”: Linear time

  • does not mean that it takes n operations
  • does mean that the work changes in a way that is proportional to n
  • is a notation for “work grows at a linear rate ”

O( n^2 ) or “Order n^2 ”: Quadratic time

O( n^3 ) or “Order n^3 ”: Cubic time

Algorithms whose complexity can be expressed in terms of a polynomial of the form

amnm^ + am-1 nm-1^ + ... + a 2 n^2 + a 1 n + a 0

are called polynomial algorithms and are of Order O( nm ).

Some algorithms even take less time than the number of elements in the problem. There is a notion of logarithmic time algorithms.

We know 103 = Taking log of both sides to base 10 , we can write it as

log 10 1000 = 3

Similarly suppose we have

26 =

Taking log of both sides to base 2

log 2 64 = 6

If the work of an algorithm can be reduced by half in every step, and in k steps we are able to solve the problem then, k and n can be related through

Evaluating Logarithms

a b^ = m

Taking log of both sides with respect to base a,

b log (^) a a = log (^) a m

or

b = log (^) a m

Thus knowing any two quantities, you can find the 3rd^ one.

Comparison of N , logN and N^2

N O(LogN) O(N^2 ) 16 4 256 64 6 4K 256 8 64K 1,024 10 1M 16,384 14 256M 131,072 17 16G 262,144 18 6.87E+ 524,288 19 2.74E+ 1,048,576 20 1.09E+ 1,073,741,824 30 1.15E+

Complexity related Problems

  1. Algorithm A runs in O(N 2 ) time, and for an input size of 4, the algorithm runs in 10 milliseconds, how long can you expect it to take to run on an input size of 16?

10 x

=> x = 160ms

  1. Algorithm A runs in O(N 3 ) time. For an input size of 10, the algorithm runs in 7 milliseconds. For another input size, the algorithm takes 189 milliseconds. What was that input size?

103 N^3

----- = ------- => N = 30

  1. Algorithm A runs in O(log 2 N) time, and for an input size of 16, the algorithm runs in 28 milliseconds, how long can you expect it to take to run on an input size of 64?

log 16 log ------------ = ------------ 28 x

How to find the log values?

b = log (^) a m , ab^ = m