QuickSort分区提供例外

时间:2014-03-29 01:47:29

标签: java

夜。我正在做一些关于算法分析的项目。它是关于quickSort,将两种不同的分区算法转换为代码,然后在报告中进行比较。

第一个算法是:

To partition a[left…right] such that a[left…j–1] are all less than or 
equal to a[j], and a[j+1…right] are all greater than or equal to a[j]: 

1. Set pivot to a[left]. 

2. Set i = left + 1 and j = right. 

3. While i ≤ j, repeat: 
 3.1. While i ≤ j and a[i] ≤ pivot, increment i. 
 3.2. While j ≥ i and a[j] ≥ pivot, decrement j. 
 3.3. If i < j, swap a[i] and a[j]. 

4. If j ≠ left, set a[left] to a[j], and a[j] to pivot. 

5. Terminate with answer j

我已经用以下内容对其进行了编码,显示无错误...

public class TestQuickSort {

    public static int partition(Comparable[] a, int left, int right) {

        Comparable p = a[left];
        int i = left + 1;
        int j = right;
        while (i <= j) {
            while (i <= j && a[i].compareTo(p) < 0) {
                i++;
            }
            while (j >= i && a[j].compareTo(p) > 0) {
                j--;
            }
            if (i < j) {
                Comparable temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
        if (j != left) {
            a[left] = a[j];
            a[j] = p;
        }

        return j;

    }

    public static void quickSort(Comparable[] a, int left, int right) {
// Sort a[left…right] into ascending order.
        if (left < right) {
            int p = partition(a, left, right);
            quickSort(a, left, p - 1);
            quickSort(a, p + 1, right);
        }
    }

    public static void main(String[] args) {
        // TODO code application logic here
        Comparable[] a = {1, 2, 6, -9, 0};
        quickSort(a, 0, a.length);
    }
}

...直到我运行它并遇到3个例外

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at TestQuickSort.partition(TestQuickSort.java:22)
    at TestQuickSort.quickSort(TestQuickSort.java:41)
    at TestQuickSort.main(TestQuickSort.java:50)
Java Result: 1

任何人都可以帮助我,我不明白为什么?这是我的while循环的问题吗?我应该使用不同类型的循环吗?

感谢任何可以回复的人。

1 个答案:

答案 0 :(得分:0)

数组中第5个元素的索引是4。 试着打电话: quickSort(a, 0, a.length-1);