Elton.fd
Elton.fd

Reputation: 1595

Sorting function using java

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?

Upvotes: 1

Views: 333

Answers (2)

Leandro
Leandro

Reputation: 376

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.

Upvotes: 0

Mat
Mat

Reputation: 206679

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.

Upvotes: 2

Related Questions