0

I have a method which does a jump search between 2x txt files.

Both files have 500 entries, but one is sorted alphabetically and the other is not (sortedEntryContacts, and unsortedEntryContacts respectively)

The method is to compare names in the unsortedEntryContacts against the sortedEntryContacts, and use the jump search until the name is found in the sortedEntryContacts.

The problem I have right now is during the last step, it jumps outside the bounds of the List, hence getting the out of bounds exception.

I've been stuck on this problem for a while now, am I can't figure out how I can check for the last step.

    public static int jumpSearchEntries(List<String> unsortedEntryContacts, List<String> sortedEntryContacts) {
        int entries = 0;
        int blocks = (int) Math.floor(Math.sqrt(sortedEntryContacts.size()));

        for (int i = 0; i != unsortedEntryContacts.size(); i++) { //Array with entries that will be compared against the sorted array.
            System.out.println("------------------------");
            System.out.println(unsortedEntryContacts.get(i) + " to be found");
            for (int j = 0; j != sortedEntryContacts.size(); j+= blocks) {
                if (sortedEntryContacts.get(j).compareTo(unsortedEntryContacts.get(i)) == 0) { // if it matches, entry found.
                    System.out.println("FOUND " + sortedEntryContacts.get(j) + " IN " + unsortedEntryContacts.get(i));
                    entries++;
                    break;
                } else if (sortedEntryContacts.get(j).compareTo(unsortedEntryContacts.get(i)) > 0) {
                    for (int k = j + 1; k != sortedEntryContacts.size(); k--) {
                        if (sortedEntryContacts.get(k).compareTo(unsortedEntryContacts.get(i)) == 0) {
                            System.out.println("FOUND " + sortedEntryContacts.get(k) + " IN " + unsortedEntryContacts.get(i));
                            entries++;
                            break;
                        }
                    }
                    break;
                }
            }
        }
        return entries;
    }
  • 1
    Use `<` in your loop control statements, not `!=`. – Andy Thomas Jan 27 '22 at 16:31
  • 1
    say size in 5, floor(sqrt(5)) == 2. i = 0, i = 2, i = 4, i = 6, ... `!=` stays true forever. Use `<` instead as @AndyThomas said. – user1984 Jan 27 '22 at 16:35
  • 1
    Does this answer your question? [What is a StringIndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/questions/40006317/what-is-a-stringindexoutofboundsexception-how-can-i-fix-it) – Elikill58 Jan 27 '22 at 17:29

0 Answers0