Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Jump search in Ruby (#5771)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <riyazulislam2003@gmail.com>
  • Loading branch information
Riyazul555 and MdRiyazulIslam authored Jun 30, 2024
1 parent 32ff9ab commit 9c4ebf1
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions program/program/implement-jump-search/ImplementJumpSearch.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
def jump_search(arr, x)
n = arr.size
block_size = Math.sqrt(n).to_i

prev = 0
while arr[[block_size, n].min - 1] < x
prev = block_size
block_size += Math.sqrt(n).to_i
return -1 if prev >= n
end

while arr[prev] < x
prev += 1
return -1 if prev == [block_size, n].min
end

return prev if arr[prev] == x

-1
end

# Example usage
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = 7
result = jump_search(arr, x)

if result != -1
puts "Element found at index #{result}"
else
puts "Element not found in the array"
end

0 comments on commit 9c4ebf1

Please sign in to comment.