Skip to content

Commit 7df4e98

Browse files
Merge pull request TheAlgorithms#124 from lvncnt/master
add KMP algorithm; improve binary search
2 parents 867ca11 + 79a73ae commit 7df4e98

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

Misc/KMP.java

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
2+
/*
3+
Implementation of Knuth–Morris–Pratt algorithm
4+
Usage:
5+
final String T = "AAAAABAAABA";
6+
final String P = "AAAA";
7+
KMPmatcher(T, P);
8+
*/
9+
public class KMP {
10+
11+
// find the starting index in string T[] that matches the search word P[]
12+
public void KMPmatcher(final String T, final String P) {
13+
final int m = T.length();
14+
final int n = P.length();
15+
final int[] pi = computePrefixFunction(P);
16+
int q = 0;
17+
for (int i = 0; i < m; i++) {
18+
while (q > 0 && T.charAt(i) != P.charAt(q)) {
19+
q = pi[q - 1];
20+
}
21+
22+
if (T.charAt(i) == P.charAt(q)) {
23+
q++;
24+
}
25+
26+
if (q == n) {
27+
System.out.println("Pattern starts: " + (i + 1 - n));
28+
q = pi[q - 1];
29+
}
30+
}
31+
32+
}
33+
34+
// return the prefix function
35+
private int[] computePrefixFunction(final String P) {
36+
final int n = P.length();
37+
final int[] pi = new int[n];
38+
pi[0] = 0;
39+
int q = 0;
40+
for (int i = 1; i < n; i++) {
41+
while (q > 0 && P.charAt(q) != P.charAt(i)) {
42+
q = pi[q - 1];
43+
}
44+
45+
if (P.charAt(q) == P.charAt(i)) {
46+
q++;
47+
}
48+
49+
pi[i] = q;
50+
51+
}
52+
53+
return pi;
54+
}
55+
}

Searches/BinarySearch.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public static <T extends Comparable<T>> int BS(T array[], T key, int lb, int ub)
2323
if ( lb > ub)
2424
return -1;
2525

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

2929
if (comp < 0)

0 commit comments

Comments
 (0)