Merge pull request #45 from prathamsharma92/prathamsharma92-patch-1-jump_search

Create jump_search.rb
This commit is contained in:
Vitor Oliveira 2021-02-06 22:49:22 -08:00 committed by GitHub
commit 328d0f68fd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

48
Searches/jump_search.rb Normal file
View file

@ -0,0 +1,48 @@
# 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.
# Time Complexity: O(√n)
def jump_search(arr, x)
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) do
prev = step;
step += Math.sqrt(n);
if (prev >= n)
return -1;
end
end
# Doing a linear search for x in block
# beginning with prev.
while (arr[prev] < x) do
prev = prev + 1;
# If we reached next block or end of
# array, element is not present.
if (prev == [step, n].min)
return -1;
end
end
# If element is found
if (arr[prev] == x)
return prev;
end
return -1;
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
index = jump_search(arr, value)
puts index == -1 ? "Element not found" : "Number #{value} is at #{index}"