Sorting: Rabin Karp

Date: 2013-11-25 |

DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)

**Big O: **O(n+m) average, O(nm) worst case when using a bad hash function and resorting to brute force

Rabin Karp relies on a hash function.  Essentially, you hash the given pattern and then compare the pattern’s hash to the given text’s hash.  If the hash matches, then you compare the actual text string to the pattern string in case the hashes matched incidentally.  Otherwise you call an updateHash function, which replaces the first text character with the next one in line.

Loop through text
If text. hash == pattern.hash{
if compare(pattern, text){
return index;
}
}
updateHash();

**Example: **An example updateHash function might look something like this:

updateHash(oldHash, base, oldChar, power, newChar, length){
return (oldHash – oldChar(base^power))*base + newChar
}

Want more like this?

The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.