TheAlgorithms-Ruby/Searches/jump_search.rb

43 lines
1 KiB
Ruby
Raw Normal View History

2019-10-21 19:39:15 +02:00
# Works only on sorted arrays.
# Finding element by creating step in array and jump ahead by fixed steps and finding element using linear search inside that steped array.
2021-02-07 07:48:51 +01:00
# Time Complexity: O(√n)
2019-10-21 19:39:15 +02:00
2021-02-07 07:48:35 +01:00
def jump_search(arr, x)
2021-02-07 08:05:54 +01:00
n = arr.length
# Finding block size to be jumped
step = Math.sqrt(n)
prev = 0
# Finding the block where element is
# present (if it is present)
while arr[[step, n].min - 1] < x
prev = step
step += Math.sqrt(n)
return -1 if prev >= n
2019-10-21 19:39:15 +02:00
end
2021-02-07 08:05:54 +01:00
# Doing a linear search for x in block
# beginning with prev.
while arr[prev] < x
prev += 1
# If we reached next block or end of
# array, element is not present.
return -1 if prev == [step, n].min
2019-10-21 19:39:15 +02:00
end
# If element is found
2021-02-07 08:05:54 +01:00
return prev if arr[prev] == x
2019-10-21 19:39:15 +02:00
2021-02-07 08:05:54 +01:00
-1
2019-10-21 19:39:15 +02:00
end
2021-02-07 08:05:54 +01:00
puts 'Enter a sorted space-separated list:'
2019-10-21 19:39:15 +02:00
arr = gets.chomp.split(' ').map(&:to_i)
2021-02-07 08:05:54 +01:00
puts 'Enter the value to be searched:'
2019-10-21 19:39:15 +02:00
value = gets.chomp.to_i
2021-02-07 07:48:31 +01:00
index = jump_search(arr, value)
2019-10-21 19:39:15 +02:00
2021-02-07 08:05:54 +01:00
puts index == -1 ? 'Element not found' : "Number #{value} is at #{index}"