Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sockets-Bita #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 59 additions & 3 deletions lib/array_intersection.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,62 @@
# Returns a new array to that contains elements in the intersection of the two input arrays
# Time complexity: ?
# Space complexity: ?
# Time complexity: o(n log m)
# Space complexity: o(n) n is the number of elements of the smallest array
# def intersection(array1, array2)
# return [] if array1 == [] || array2 == []
# return [] if array1 == nil || array2 == nil
# intersection = []
# array1.each do |i|
# array2.each do |j|
# if i == j
# intersection.push(i)
# end
# end
# end
# return intersection
# end
def intersection(array1, array2)
raise NotImplementedError
if array1 == nil || array2 == nil
return []
else
intersection = []
if array1.length >= array2.length
i = 0
array = array1.sort
array2.length.times do
if binary_search(array, array2[i])
intersection.push(array2[i])
end
i += 1
end
return intersection
else
array = array2.sort

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this else you're not setting i to zero.

array1.length.times do
if binary_search(array, array1[i])
intersection.push(array1[i])
end
i += 1
end
return intersection
end
end
end

def binary_search(array, value_to_find)
mid = array.length / 2
i = 0
j = array.length - 1
while i < j

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really what you want for the while loop here? What if the array is 1 element in size?

if array[mid] == value_to_find
return true
elsif array[mid] < value_to_find
i = mid + 1
j = array.length - 1

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are ending up reseting the top value of your search criteria here! This line shouldn't be here!

mid = (i + j) / 2
else
j = mid - 1
mid = (i + j) / 2
end
end
return false
end