Implemented linear and binary search with tests.

This commit is contained in:
Thomas Huang 2017-10-01 12:56:35 -05:00
parent 5cd15d08d8
commit 716890e4c8
2 changed files with 41 additions and 0 deletions

23
Searches/binary_search.rb Normal file
View file

@ -0,0 +1,23 @@
=begin
Searches through a list for a value in O(log(n)) time.
The list must be sorted.
=end
def binary_search(array, key)
front = 0
back = array.length - 1
while front <= back
middle = (front + back) / 2
return middle if array[middle] == key
key < array[middle] ?
back = middle - 1 : front = middle + 1
end
nil
end
puts "Enter a sorted space-separated list:"
arr = gets.chomp.split(' ').map(&:to_i)
puts "Enter the value to be searched:"
value = gets.chomp.to_i
puts binary_search(arr, value) != nil ?
"Found at index #{binary_search(arr, value)}" :
"Not found"

18
Searches/linear_search.rb Normal file
View file

@ -0,0 +1,18 @@
=begin
Looks through array for a value in O(n) time.
Array does not need to be sorted.
=end
def linear_search(array, key)
array.each_with_index do |current, index|
return index if current == key
end
return nil
end
puts "Enter a space-separated list:"
arr = gets.chomp.split(' ').map(&:to_i)
puts "Enter a value to be searched:"
key = gets.chomp.to_i
puts linear_search(arr, key) != nil ?
"Found at index #{linear_search(arr, key)}" :
"Not found"