mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-11-16 19:50:00 +01:00
Implemented linear and binary search with tests.
This commit is contained in:
parent
5cd15d08d8
commit
716890e4c8
2 changed files with 41 additions and 0 deletions
23
Searches/binary_search.rb
Normal file
23
Searches/binary_search.rb
Normal 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
18
Searches/linear_search.rb
Normal 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"
|
Loading…
Reference in a new issue