QuickSort IndexOutOfBound异常arraylist

问题描述 投票:2回答:1

你好我试着编写QuickSort代码,但是我总是遇到一个超出范围的索引?我的代码如下:

public class QuickSort
{
    public void quickSort(ArrayList<Integer> A, int p, int r)
    {
        if (p < r) {
            int q = partition(A, p, r);
            quickSort(A, p, q - 1);
            quickSort(A, q + 1, r);
        }
    }
    public int partition(ArrayList<Integer> A, int p, int r) {
        int x = A.get(r);
        int i = p - 1;
        for (int j = p ; j < r; j++) {
            if (A.get(j) <= x) {
                i++;
                Collections.swap(A, A.get(i), A.get(j));
            }
        }
        Collections.swap(A, A.get(i + 1), A.get(r));
        return (i + 1);
    }
}

我正在使用书中的代码:“算法简介”

我正在尝试快速排序ArrayList A.

public class TestDriver
{
    public static void testQuick() {
        //Laver et random array A
        ArrayList<Integer> A = new ArrayList<>();
        for (int i = 1; i <12; i++) {
            A.add(i);
        }
        Collections.shuffle(A);
        int n = A.size();
        QuickSort qs = new QuickSort();
        System.out.println("The Array");
        System.out.println(A);
        qs.quickSort(A, 0, (n - 1));
        System.out.println("The Array after QuickSort");
        System.out.println(A);
        System.out.println("");

    }
}
java arraylist indexoutofboundsexception quicksort
1个回答
1
投票

问题是Collections.swap(A, A.get(i), A.get(j)); - 这将尝试使用A.get(i)中的值作为列表中的索引,并且如果i中的值大于A.size(),则显然会抛出一个超出范围的异常。

所以用你想要交换的位置替换它们:

Collections.swap(A, i, j);

Collections.swap(A, (i + 1), r);
© www.soinside.com 2019 - 2024. All rights reserved.