1

I am writing a java application.

  ArrayList<int[]> list = new ArrayList<int[]>();

  double[] array = new double[10];  

I have written a function to sort the array and sort list based on the array sort. But my function doesnt work correctly.

  public void sort() {
    int n = array.length;
    for (int i = 1; i < n; i++) {
        double m = array[i];
        int[] d = list.get(i);
        int j = i - 1;
        while ((j >= 0) && (array[j] > m))
        {
            array[j+1] = array[j--];
            list.set(j+1, list.get(j--));
        }
        array[j+1]=m;
        list.set(j+1, d);
    }
}

It has java.lang.ArrayIndexOutOfBoundsException in line :

          list.set(j+1, list.get(j--));

How can I solve the problem and sort the list based on the sort of array?

2
  • Where is this line in your code? choromosomes.set(j+1, choromosomes.get(j--)); Commented Jan 21, 2012 at 14:39
  • The line the error is from isn't it the code you've posted. Can you show that code? Commented Jan 21, 2012 at 14:39

2 Answers 2

2

When i==1, j is initially 0.

Assuming array[0] > array[1], the if block is entered, and after:

array[j+1] = array[j--];

j == -1, so you can't use it to index list. The second decrement looks suspicious too.

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

Comments

0

I think this link has everything you need: http://www.leepoint.net/notes-java/data/arrays/70sorting.html

Basically to sort an array you'll use java.util.Arrays' sort method and for ArrayList you'll use java.util.Collections' sort method.

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.