Skip to content

Instantly share code, notes, and snippets.

@dialektike
Created June 18, 2021 14:30
Show Gist options
  • Save dialektike/d78cf8aa7db8055e2db6ba8a3566aeed to your computer and use it in GitHub Desktop.
Save dialektike/d78cf8aa7db8055e2db6ba8a3566aeed to your computer and use it in GitHub Desktop.
linear search
use std::time::Instant;
fn main() {
println!("Hello, world!");
let unsort: [i32; 100] = [
49, 76, 80, 74, 18, 16, 5, 71, 65, 6, 3, 12, 36, 75, 22, 19, 93, 97, 43, 85, 7, 10, 67, 69,
79, 51, 31, 60, 20, 50, 82, 44, 59, 33, 95, 98, 72, 90, 57, 39, 17, 94, 42, 77, 96, 68, 56,
66, 81, 86, 48, 88, 87, 38, 78, 73, 11, 84, 8, 14, 58, 37, 9, 25, 47, 28, 27, 83, 63, 100,
91, 4, 13, 40, 15, 32, 62, 54, 64, 35, 99, 53, 34, 30, 26, 29, 89, 2, 23, 55, 92, 1, 46,
21, 70, 61, 24, 52, 41, 45,
];
let now = Instant::now();
linear_search(&unsort, 45);
let new_now = Instant::now();
println!("{:?}", new_now.checked_duration_since(now));
let now = Instant::now();
recursive_linear_search(&unsort, 45, 1);
let new_now = Instant::now();
println!("{:?}", new_now.checked_duration_since(now));
}
fn linear_search(lis: &[i32], n: i32) {
let mut temp: i32 = 0;
for i in 0..lis.len(){
temp = temp + 1;
if lis[i] == n {
println!("{:?}",temp);
break;
}
}
}
fn recursive_linear_search(lis: &[i32], n: i32, i: i32){
if lis[i as usize] == n {
println!("{:?}", i + 1)
} else if i == lis.len() as i32 {
println!("{:?}", "값이 없습니다!")
} else {
recursive_linear_search(lis, n, i + 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment