def search(arr, n) for i in 0..arr.length-1 if(arr[i] == n) return i end end return -1 end arr = [5, 3, 6, 2, 1, 4] n = 2 # Element to be searched. puts "The Array elements are " for i in 0..arr.length-1 puts arr[i] end puts "\nElement to be searched #{n}" index = search(arr, n) if(index == -1) puts "Element is not present in the array" else puts "The element #{n} is present at index : #{index}" end
The above code is quite simple,
We will be searching the element 2,
n = 2 # Element to be searched.
From the array,
arr = [5, 3, 6, 2, 1, 4]
Next, we pass the array and the element 2, to the search(...) method.
index = search(arr, n)
def search(arr, n) for i in 0..arr.length-1 if(arr[i] == n) return i end end return -1 end
We need to search the element 2 from the below array.
So, we run a for loop. Starting from the 1st location to the end of the array.
for i in 0..arr.length-1 if(arr[i] == n) return i end end
And at every step, we keep on checking if the element is present in the array or not.
if(arr[i] == n) return i end
If we find the element, we return that particular location.
return i
But, what if we are searching for an element that is not present in the array?
Say, we are searching for number 8. Which is not present in the array.
In that case, we return -1.
return -1
Which states the number is not found.
Finally, the returned value is stored in the index variable.
index = search(arr, n)
And we print it using :
puts "The element #{n} is present at index : #{index}"