Created
July 13, 2016 07:27
-
-
Save scturtle/b686cd8d0cf2ffa0009130636507338e to your computer and use it in GitHub Desktop.
horspool search algorithm in rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn horspool<T: Eq+Hash>(haystack: &[T], needle: &[T]) -> isize { | |
let hlen = haystack.len(); | |
let nlen = needle.len(); | |
if nlen == 0 { return 0 } | |
// jump table | |
let jmp: HashMap<&T, usize> = needle.iter().zip((1..nlen).rev()).collect(); | |
let last = nlen - 1; | |
let mut j = 0; | |
while j <= hlen - nlen { | |
// search backward | |
let mut i = last; | |
while haystack[j + i] == needle[i] { | |
if i == 0 {/* found */ return j as isize } | |
i -= 1 | |
} | |
// jump according to the last one of haystack | |
j += *jmp.get(&haystack[j + last]).unwrap_or(&nlen); | |
} | |
/* not found */ -1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment