Files
hello-algo/en/codes/ruby/chapter_searching/linear_search.rb
Yudong Jin 2778a6f9c7 Translate all code to English (#1836)
* Review the EN heading format.

* Fix pythontutor headings.

* Fix pythontutor headings.

* bug fixes

* Fix headings in **/summary.md

* Revisit the CN-to-EN translation for Python code using Claude-4.5

* Revisit the CN-to-EN translation for Java code using Claude-4.5

* Revisit the CN-to-EN translation for Cpp code using Claude-4.5.

* Fix the dictionary.

* Fix cpp code translation for the multipart strings.

* Translate Go code to English.

* Update workflows to test EN code.

* Add EN translation for C.

* Add EN translation for CSharp.

* Add EN translation for Swift.

* Trigger the CI check.

* Revert.

* Update en/hash_map.md

* Add the EN version of Dart code.

* Add the EN version of Kotlin code.

* Add missing code files.

* Add the EN version of JavaScript code.

* Add the EN version of TypeScript code.

* Fix the workflows.

* Add the EN version of Ruby code.

* Add the EN version of Rust code.

* Update the CI check for the English version  code.

* Update Python CI check.

* Fix cmakelists for en/C code.

* Fix Ruby comments
2025-12-31 07:44:52 +08:00

45 lines
1.0 KiB
Ruby

=begin
File: linear_search.rb
Created Time: 2024-04-09
Author: Blue Bean (lonnnnnnner@gmail.com)
=end
require_relative '../utils/list_node'
### Linear search (array) ###
def linear_search_array(nums, target)
# Traverse array
for i in 0...nums.length
return i if nums[i] == target # Found the target element, return its index
end
-1 # Target element not found, return -1
end
### Linear search (linked list) ###
def linear_search_linkedlist(head, target)
# Traverse the linked list
while head
return head if head.val == target # Found the target node, return it
head = head.next
end
nil # Target node not found, return None
end
### Driver Code ###
if __FILE__ == $0
target = 3
# Perform linear search in array
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
index = linear_search_array(nums, target)
puts "Index of target element 3 = #{index}"
# Perform linear search in linked list
head = arr_to_linked_list(nums)
node = linear_search_linkedlist(head, target)
puts "Node object for target value 3 is #{node}"
end