Merge pull request #9 from thomashhuang/master

Implemented linear and binary search with tests.
This commit is contained in:
Chetan Kaushik 2017-11-05 22:56:22 +05:30 committed by GitHub
commit 85786644ca
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
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"