-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathlinearSearchIteratively.rb
49 lines (37 loc) · 1.43 KB
/
linearSearchIteratively.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def start_program #method defination
array_size = take_array_size_from_user
array = take_array_elements(array_size)
element = element_to_search
index_found_at = linear_search(array, element)
if index_found_at == -1
puts "Ughh... the element you want to search is not present in the given array"
else
puts "You Got it... the element is present in the given array at index #{index_found_at}"
end
end
def take_array_size_from_user
puts "Enter the size of the array"
array_size = gets.chomp.to_i
puts "Array size given by you is #{array_size}"
return array_size
end
def take_array_elements(array_size)
array = [] #initializing an empty array
array_size.times do |var| #looping array's size times to get that number of elements to fill in array
puts "Enter array element no. #{var}"
array << gets.chomp.to_i #takes the input in form of string and convert it to integer
end
return array
end
def element_to_search
puts "Enter element to search in array"
element = gets.chomp.to_i
return element
end
def linear_search(array, element)
array.each_with_index do |var, index| #looping through the array on each element with it's index
return index if var == element # return the element's index if matches the condition
end
return -1 #if not found in the array returns -1
end
start_program #calls the method for execution