Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8213169
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T11:01:12+00:00 2026-06-07T11:01:12+00:00

Good day, everyone! I have here a program that sorts 50,000 words from a

  • 0

Good day, everyone! I have here a program that sorts 50,000 words from a file using merge sort. I followed Thomas Cormen’s pseudocode in his Introduction to Algorithms and it seems right when I’m “debuuging” it by hand manually. However, when I run the program it says Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 . Yes, I think it is due to the large NO_OF_WORDS (ie, 50,000) but even though I decreased it to 10, still, it shows the same error.

import java.io.*;
import java.util.*;

public class SortingAnalysis {

    public static void merge(String[] A, int p, int q, int r) {
        int n1 = q-p+1;
        int n2 = r-q;
        String[] L = new String[n1+1];
        String[] R = new String[n2+1];
        for (int i=1; i<n1; i++) {
            L[i] = A[p+i-1];
        }
        for (int j=1; j<n2; j++) {
            R[j] = A[q+j];
        }
        L[n1+1] = "zzzzz"; //for infinity because if I use Math.floor, it will return a double
        R[n2+1] = "zzzzz";
        int i=1;
        int j=1;
        for (int k=p; k<=r; k++) {
            int comparison = L[i].compareTo(R[j]);
            if (comparison <= 0){
                A[k] = L[i];
                i++;
            }
            else {
                A[k] = R[j];
                j++;
            }

        }

    }

    public static void mergeSort (String[] A, int p, int r) {
        if (p<r) {
            int q = (p+r)/2;
            mergeSort(A, p, q);
            mergeSort(A, q+1, r);
            merge(A, p, q, r);
        }
    }

    public static void main(String[] args) {
        final int NO_OF_WORDS = 50000;
        try {
            Scanner file = new Scanner(new File(args[0]));
            String[] words = new String[NO_OF_WORDS];

            int i = 0;
            while(file.hasNext() && i < NO_OF_WORDS) {
                words[i] = file.next();
                i++;
            }
            long start = System.currentTimeMillis();

            mergeSort(words, 0, words.length-1);

            long end = System.currentTimeMillis();
            System.out.println("Sorted Words: ");
            for(int j = 0; j < words.length; j++) {
                System.out.println(words[j]);
            }   
            System.out.print("Running time: " + (end - start) + "ms");

        }
        catch(SecurityException securityException) {
            System.err.println("Error");
            System.exit(1);
        }
        catch(FileNotFoundException fileNotFoundException) {
            System.err.println("Error");
            System.exit(1);
        } 
    } 
}

I think it’s because of the declaration of String[] L and R. Or not. Please help me what’s the problem. Thank you very much!

EDIT
Cormen’s Pseudocode

MERGE(A, p, q, r )
n1 ← q − p + 1
n2 ←r − q
create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
for i ← 1 to n1
     do L[i ] ← A[p + i − 1]
for j ← 1 to n2
     do R[ j ] ← A[q + j ]
L[n1 + 1]←∞
R[n2 + 1]←∞
i ← 1
j ← 1
for k ← p to r
     do if L[i ] ≤ R[ j ]
        then A[k] ← L[i ]
             i ←i + 1
        else A[k] ← R[ j ]
             j ← j + 1
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T11:01:14+00:00Added an answer on June 7, 2026 at 11:01 am

    I don’t know what is your pseudocode but your implementation seems wrong. I’ve look at the wikipedia merge sort and it’s quite different.

    So I will not give you the full working algorithm here. I’ll just give you the solution to resolve your problem of indexOutOfBounds but you still have to work more on your implementation.

    In Java when you do that :

    String[] L = new String[5];
    

    You declare an array of string that can contains 5 strings within.

    The access to those strings is made this way : L[anIndex].

    The first element is at index 0.

    So if you have an array of size 5 then the last element is at index 4 (because we start from 0).

    In your code you do this :

    String[] L = new String[n1+1];
    String[] R = new String[n2+1];
    

    then :

    L[n1+1] = "zzzzz";
    R[n2+1] = "zzzzz";
    

    So here you always try to access a string at an index that doesn’t exist.
    The last element in each array is respectively n1 and n2 (because arrays size are n1+1 and n2+1 ).

    I hope you’ll understand better how array works in Java with this explanation. Now you have to improve your implementation because it’s still not working. Maybe give us the pseudocode you use if you don’t understand it well.

    EDIT :

    Ok I made some correction.

    Here is the working algorithm. I’ve had to change several index to fit Java “based-0 arrays”, take a look :

    import java.io.*;
    import java.util.*;
    
    public class SortingAnalysis {
    
        public static void merge(String[] A, int p, int q, int r) {
            int n1 = q-p+1;
            int n2 = r-q;
            if(A[p]==null || A[q]==null)return;
            String[] L = new String[n1+1];
            String[] R = new String[n2+1];
            for (int i=0; i<n1; i++) {
                L[i] = A[p+i];
            }
            for (int j=0; j<n2; j++) {
                R[j] = A[q+j +1];
            }
            L[n1] = "zzzzz"; //for infinity because if I use Math.floor, it will return a double
            R[n2] = "zzzzz";
            int i=0;
            int j=0;
            for (int k=p; k<=r; k++) {
                int comparison = L[i].compareTo(R[j]);
                if (comparison <= 0){
                    A[k] = L[i];
                    i++;
                }
                else {
                    A[k] = R[j];
                    j++;
                }
    
            }
    
        }
    
        public static void mergeSort (String[] A, int p, int r) {
            if (p<r) {
                int q = (p+r)/2;
                mergeSort(A, p, q);
                mergeSort(A, q+1, r);
                merge(A, p, q, r);
            }
        }
    
        public static void main(String[] args) {
            final int NO_OF_WORDS = 50000;
            try {
                Scanner file = new Scanner("bla blya blay byla ybla");
                ArrayList<String> words = new ArrayList<String>();
    
                while(file.hasNext() && words.size() < NO_OF_WORDS) {
                    words.add(file.next());
                }
                String [] wordsArray = new String[words.size()];
                words.toArray(wordsArray);
                long start = System.currentTimeMillis();
    
                mergeSort(wordsArray, 0, wordsArray.length-1);
    
                long end = System.currentTimeMillis();
                System.out.println("Sorted Words: ");
                for(int j = 0; j < wordsArray.length; j++) {
                    System.out.println(wordsArray[j]);
                }   
                System.out.print("Running time: " + (end - start) + "ms");
    
            }
            catch(SecurityException securityException) {
                System.err.println("Error");
                System.exit(1);
            }
    
        }
    }
    

    Note that I’ve change your Main, now I use an arrayList to avoid null value, if your text contains less words than the original array size. With your solution if you don’t fill the 50000 words you get null in the array and then nullPointerException in the merge algo.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Good day everyone. I have an audio class, that plays a .wav file. But
Good day everyone. I have a question about making and using derived classes of
Good Day Everyone, I have a program (lets call it 'A'), which is called
Good day, I have a question here. I am trying to fetch image from
Good day everyone. I have been having the same problem all day at work
Good day everyone! I have a problem regarding my date. It needs to be
Good day everyone, I am building a page in ASP.NET, and using Master Pages
Good day everyone, this is one of those areas that is a little over
Good day everyone! I am using the T-SQL ISDATE() function with a date column
Good day everyone, I have the following XML data : <?xml version=1.0 encoding=utf-8 ?>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.