Data-structures 1

Complexity

Algorithm runtime #definition

Number of operations depending on the size of input is called the algorithm runtime

Worst and best cases #definition

1.Worst case is the most number of operations algorithm can executeover all inputs2.Best case is the least number of operations algorithm can executeover all inputs

Average case #definition

Average case is the number of operations algorithm will execute,averaged over all possible inputsIt is important to devise the probability distribution over inputs,as the average is not just mathematical avg, it is a weighted average

Example

Let us examine code of a linear search for an element k in array arr
i = 1                            # 1 time
while i <= n:                    # n+1 times
	if arr[i] == k: return True  # n times
	i += 1                       # n times
return False                     # 1 time
								 # _________
                                 # 3n + 3 in total
Worst case is 3n+3, when there is no element k in arrBest case is 3, when element k is first in arrLet fi(n) represent runtime when k is on i-th place in arrf1(n)=3f2(n)=6fn(n)=3n}i=1n+1fi(n)=3+6++3n=3n(n+1)2fn+1(n)=3n+3Average case is 3n(n+1)2n=3(n+1)2

Big-O, Omega, "order" of functions #definition

f(n)=O(g(n))α>0R,NN0:nN:f(n)αg(n)f(n)=o(g(n))α>0R:NN0:nN:f(n)αg(n)f(n)=Ω(g(n))α>0R,NN0:nN:f(n)αg(n)f(n)=ω(g(n))α>0R:NN0:nN:f(n)αg(n)f(n)=Θ(g(n))f(g(n))=O(g(n)) and f(g(n))=Ω(g(n))3n2+5=O(n2)?f(n)=3n2+5,g(n)=n23n2+53n2+5n2=8n2f(n)8g(n)f(n)=O(g(n))

Data structures

Array #definition

"Linear" ordered data collection with randow access by index|123n|

Stack #definition

"Linear" ordered data collection with restricted access - LIFO (Last In - First Out)Stack is usually implemented as array with a counter, pointing to the "top"

Parenthesis validation

e.g. "[](){}[(((<>)))]"0. Read one parenthesis1. Opening parenthesis? Push to stack2. Closing parenthesis? Pop last parenthesis on stack, check if paired2.1 If not paired (or stack is empty), abort, invalid2.2 If paired, continue to 03. Input is over? Check if stack is empty3.1 If empty, valid3.2 If not empty, invalid

Postfix Polish notation

operand1 operand2 operation operand3 operation ...e.g. 2 3 + 8 *0. Read one element1. Operand? Push to stack2. Operation? Pop n operands from stack, perform operation, push result to stackcontinue to 03. Input is over?3.1 If stack has more than one element, invalid3.2 If stack has one element, it is the result

Queue #definition

"Linear" ordered data collection with restricted access - FIFO (First In - First Out)