Chennai.rb meet-up 25-june-2016
Abhishek Yadav
ரூபீ ப்ரோக்ராமர்
Co-organizer: Chennai.rb
## Search an element in the given, sorted array
def search1(arr, input)
i = 0
while i < arr.size do
return i if arr[i] == input
i += 1
end
end
input = 73
arr = [3, 10, 22, 72, 100, 344]
search1(73, arr)
Sequencial search
In the worst case it has to go ever the whole array
## Search an element in the given, sorted array
def bsearch(arr, input, start=0, finish=arr.size-1)
if start == finish
return arr[start] == input ? start : nil
end
mid = start + (finish - start)/2
case
when input == arr[mid] then return mid
when input < arr[mid] then return bsearch(arr, input, start, mid)
when input > arr[mid] then return bsearch(arr, input, mid+1, finish)
end
end
input = 73
arr = [3, 10, 22, 72, 100, 344]
search1(73, arr)
Binary search
Binary search
visualization: searching 33
Binary search
# Selection sort (very slow on large lists)
a = [9,8,6,1,2,5,4,3,9,50,12,11]
n = a.size - 1
n.times do |i|
index_min = i
(i + 1).upto(n) do |j|
index_min = j if a[j] < a[index_min]
end
# Yep, in ruby I can do that, no aux variable. w00t!
a[i], a[index_min] = a[index_min], a[i] if index_min != i
end
## Credit: https://gist.github.com/brianstorti/953310
users = User.where(active: true).to_a
## TODO
# What is the time complexity here?
def foo(arr)
1.upto(100).each do |i|
1.upto(1000).each do |j|
puts arr[i] + arr[j]
end
end
end