Skip to content

add KMP algorithm; improve binary search #124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions Misc/KMP.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

/*
Implementation of Knuth–Morris–Pratt algorithm
Usage:
final String T = "AAAAABAAABA";
final String P = "AAAA";
KMPmatcher(T, P);
*/
public class KMP {

// find the starting index in string T[] that matches the search word P[]
public void KMPmatcher(final String T, final String P) {
final int m = T.length();
final int n = P.length();
final int[] pi = computePrefixFunction(P);
int q = 0;
for (int i = 0; i < m; i++) {
while (q > 0 && T.charAt(i) != P.charAt(q)) {
q = pi[q - 1];
}

if (T.charAt(i) == P.charAt(q)) {
q++;
}

if (q == n) {
System.out.println("Pattern starts: " + (i + 1 - n));
q = pi[q - 1];
}
}

}

// return the prefix function
private int[] computePrefixFunction(final String P) {
final int n = P.length();
final int[] pi = new int[n];
pi[0] = 0;
int q = 0;
for (int i = 1; i < n; i++) {
while (q > 0 && P.charAt(q) != P.charAt(i)) {
q = pi[q - 1];
}

if (P.charAt(q) == P.charAt(i)) {
q++;
}

pi[i] = q;

}

return pi;
}
}
2 changes: 1 addition & 1 deletion Searches/BinarySearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static <T extends Comparable<T>> int BS(T array[], T key, int lb, int ub)
if ( lb > ub)
return -1;

int mid = (ub+lb)/2;
int mid = (ub+lb) >>> 1;
int comp = key.compareTo(array[mid]);

if (comp < 0)
Expand Down