0
import java.util.Scanner;
class Little_elephant
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        int t = scan.nextInt();
        int arr[] = new int[100];
        int inversions, localInversions;
        for(int i = 0; i < t; i++)
        {
            inversions = 0;
            localInversions = 0;
            int n = scan.nextInt();
            for(int j = 0; j < n; j++)
            {
                arr[j] = scan.nextInt();
            }
            for(int j = 0; j < n - 1; j++)
            {
                for(int k = j + 1; j < n; k++)
                {
                    if(arr[j] > arr[k])
                    {
                        inversions++;
                    }
                }
                if(arr[j] > arr[j+1])
                    localInversions++;
            }
            if(inversions == localInversions)
                System.out.println("YES");
            else
                System.out.println("No");
            }
        }
    }
}    

The program is showing no error on compilation but is getting an array index out of bounds exception at 23rd line. Also the error is when I try more than one case i.e t>1. Please someone help me!

3
  • So what's the value of n? Ideally, show a minimal reproducible example... this looks like it's more complicated than it needs to be to demonstrate the problem, and I suspect that while reducing it you'll find the answer. Commented May 19, 2016 at 13:24
  • Please include some input, as well as the expected output and/or describe the semantics of your program. Commented May 19, 2016 at 13:24
  • 1
    This question could be closed as off topic because it does not include an MCVE. Please include the values you use and you should also work on improving your variable names. Commented May 19, 2016 at 13:28

2 Answers 2

1

You have a loop for(int k = j + 1; j < n; k++)
You're increasing k but the condition is on j

Sign up to request clarification or add additional context in comments.

Comments

0

Your nested for loop for k on line 21 is not stating a terminating clause for k, but rather for j. So right now your loop looks like this:

for(int k = j + 1; j < n; k++)

Where it should be saying:

for(int k = j + 1; k < n; k++)

Notice how k is less than n, not j less than n.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.