CSCE 222 Lecture 3

From Notes
Jump to navigation Jump to search

« previous | Monday, January 24, 2011 | next »


Intro to Ruby

Elementary Operations

  • assignment ( = )
  • arithmetic ( + - * / % )
  • boolean operations ( && || & | ^ ! )
  • comparisons ( < <= == >= > )
  • indexed (array) access ( [i] )

All have constant running time, i.e. time.

Statements

block 1 { }
block 2 { }
block 3 { }
# ...
block k { }

If block k takes time, then to execute all blocks.

Control Structures

if BoolExpr then
  block 1 { }
else
  block 2 { }
end

If evaluation of BoolExpr takes time and execution of block k takes time, then to execute if statement.

For Loop

for k in (a..b) do
  block 1 { }
end

If block 1 takes time, then for entire for statement.

Function calls

def f( params )
  block 1 { }
end

If is time to assign parameters and is the time to execute block 1 given params, then for function call.

Example

def bubble_sort(list)      # O(1) params
  list = list.dup      # O(n)
  for i in 0..(list.length - 2) do      # O(n^2) (runs (O(n) n times)
    for j in 0..(list.length - i - 2) do      # O(n) (runs O(1) n times)
      list[j], list[j+1] = list[j+1], list[j] if list[j+1] < list[j]      # O(1)
    end
  end
  return list      # O(!)
end  # O(1) + O(n) + O(n^2) + O(n) + O(1) = O(n^2)