Text Search Engine Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Text Search Engine runs in O(n log n) time and O(n) space, in Java as in every other language.
- ✓No suffix array in the JDK. You get java.util.Arrays for sorting and binary search, String.getBytes(StandardCharsets.UTF_8) from java.nio.charset for the corpus bytes, java.text.BreakIterator for locale-aware word segmentation when you tokenize, java.text.Collator for linguistic term ordering, and java.util.regex for the scan fallback.
- ✓Primitive arrays everywhere the API permits (byte[] corpus, int[] suffix array, int[] rank), boxing confined to the one place the JDK forces it.
- ✓The Java trap: byte is signed in Java and in none of the other seven languages here. A UTF-8 continuation or lead byte, 0x80 through 0xFF, reads as -128 through -1, so every suffix starting with a non-ASCII character sorts before every ASCII suffix.
- ✓Arrays.sort(int[]) is a tuned dual-pivot quicksort with no allocation, and you lose it the instant you need a comparator, because there is no comparator overload for primitive arrays.
What Text Search Engine actually is
Text Search Engine in Java: what you actually reach for
Java implementation
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public final class SuffixIndex {
private final byte[] text;
private final int[] sa;
public SuffixIndex(String corpus) {
this.text = corpus.getBytes(StandardCharsets.UTF_8);
this.sa = build(this.text);
}
private static int[] build(byte[] t) {
final int n = t.length;
Integer[] order = new Integer[n]; // int[] takes no Comparator
int[] rank = new int[n], nxt = new int[n];
for (int i = 0; i < n; i++) {
order[i] = i;
rank[i] = t[i] & 0xFF; // byte is signed: unsign it
}
for (int k = 1; k < n; k <<= 1) {
final int kk = k;
final int[] r = rank;
Arrays.sort(order, (a, b) -> {
if (r[a] != r[b]) return Integer.compare(r[a], r[b]);
int ra = a + kk < n ? r[a + kk] : -1;
int rb = b + kk < n ? r[b + kk] : -1;
return Integer.compare(ra, rb);
});
nxt[order[0]] = 0;
for (int i = 1; i < n; i++) {
int p = order[i - 1], c = order[i];
int pk = p + kk < n ? r[p + kk] : -1;
int ck = c + kk < n ? r[c + kk] : -1;
nxt[c] = nxt[p] + ((r[p] == r[c] && pk == ck) ? 0 : 1);
}
System.arraycopy(nxt, 0, rank, 0, n);
if (rank[order[n - 1]] == n - 1) break;
}
int[] out = new int[n];
for (int i = 0; i < n; i++) out[i] = order[i];
return out;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Text Search Engine?
No suffix array in the JDK. You get java.util.Arrays for sorting and binary search, String.getBytes(StandardCharsets.UTF_8) from java.nio.charset for the corpus bytes, java.text.BreakIterator for locale-aware word segmentation when you tokenize, java.text.Collator for linguistic term ordering, and java.util.regex for the scan fallback. Note that Arrays.binarySearch has no overload taking a comparator over int[], so the lower-bound search is yours to write. The ecosystem answer for anything ranked is Apache Lucene: org.apache.lucene.index.IndexWriter, DirectoryReader and IndexSearcher, with StandardAnalyzer doing the tokenization.
What is the most common Java mistake when implementing Text Search Engine?
byte is signed in Java and in none of the other seven languages here. A UTF-8 continuation or lead byte, 0x80 through 0xFF, reads as -128 through -1, so every suffix starting with a non-ASCII character sorts before every ASCII suffix. The array is still a valid permutation, the binary search still terminates, and English test corpora pass perfectly; the engine simply stops finding Chinese, Arabic and accented French. Mask with & 0xFF at every single read, including inside the comparator and the rank seed. Related: modern String.substring copies its char array rather than sharing it, so materialising suffixes is now quadratic in memory as well as in time.
How does Text Search Engine actually perform in Java?
Arrays.sort(int[]) is a tuned dual-pivot quicksort with no allocation, and you lose it the instant you need a comparator, because there is no comparator overload for primitive arrays. Boxing to Integer[] costs n allocations once at setup, in fact fewer than n because Integer.valueOf caches -128..127, plus a pointer dereference on both sides of every compare in every round, and the boxes outlive the sort, so escape analysis cannot eliminate them. TimSort over Integer[] also allocates an O(n) working array on each round, which Arrays.sort(int[]) does not. The comparator itself runs interpreted for the first several thousand invocations before C2 inlines it, so the early rounds are the slow ones. Compact strings back Latin-1 content with byte[], so getBytes(UTF_8) on ASCII is close to a straight copy. Time complexity is O(n log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.