mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-09 05:41:47 +08:00
* 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
55 lines
1.5 KiB
Rust
55 lines
1.5 KiB
Rust
/*
|
|
* File: linear_search.rs
|
|
* Created Time: 2023-07-09
|
|
* Author: codingonion (coderonion@gmail.com)
|
|
*/
|
|
|
|
use hello_algo_rust::include::ListNode;
|
|
use std::cell::RefCell;
|
|
use std::rc::Rc;
|
|
|
|
/* Linear search (array) */
|
|
fn linear_search_array(nums: &[i32], target: i32) -> i32 {
|
|
// Traverse array
|
|
for (i, num) in nums.iter().enumerate() {
|
|
// Found the target element, return its index
|
|
if num == &target {
|
|
return i as i32;
|
|
}
|
|
}
|
|
// Target element not found, return -1
|
|
return -1;
|
|
}
|
|
|
|
/* Linear search (linked list) */
|
|
fn linear_search_linked_list(
|
|
head: Rc<RefCell<ListNode<i32>>>,
|
|
target: i32,
|
|
) -> Option<Rc<RefCell<ListNode<i32>>>> {
|
|
// Found the target node, return it
|
|
if head.borrow().val == target {
|
|
return Some(head);
|
|
};
|
|
// Found the target node, return it
|
|
if let Some(node) = &head.borrow_mut().next {
|
|
return linear_search_linked_list(node.clone(), target);
|
|
}
|
|
// Target node not found, return None
|
|
return None;
|
|
}
|
|
|
|
/* Driver Code */
|
|
pub fn main() {
|
|
let target = 3;
|
|
|
|
/* Perform linear search in array */
|
|
let nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
|
let index = linear_search_array(&nums, target);
|
|
println!("Index of target element 3 = {}", index);
|
|
|
|
/* Perform linear search in linked list */
|
|
let head = ListNode::arr_to_linked_list(&nums);
|
|
let node = linear_search_linked_list(head.unwrap(), target);
|
|
println!("Node object corresponding to target node value 3 is {:?}", node);
|
|
}
|