Skip to content

Instantly share code, notes, and snippets.

@scturtle
Created July 13, 2016 07:27
Show Gist options
  • Save scturtle/b686cd8d0cf2ffa0009130636507338e to your computer and use it in GitHub Desktop.
Save scturtle/b686cd8d0cf2ffa0009130636507338e to your computer and use it in GitHub Desktop.
horspool search algorithm in rust
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