QuickSort用于排序数组

时间:2016-05-07 03:36:51

标签: java quicksort

这是我的QuickSort算法的代码实现;但是,它不适用于排序数组。可能是什么问题?

    public void insertionSort(ArrayList<String> data, int firstIndex,
    int numberToSort) {
    if (firstIndex + numberToSort > data.size())
        System.out.println("Index is larger then the date size");
    else {
        for (int i = 1; i < numberToSort; i++) {
            for (int j = 0; j < i; j++) {
                if (data.get(firstIndex + j).compareTo(
                        data.get(firstIndex + i)) > 0)
                    Collections.swap(data, firstIndex + i, firstIndex + j);
            }
        }
    }
}

@Override
public void quickSort(ArrayList<String> data, int firstIndex,
        int numberToSort) {
    if (firstIndex + numberToSort > data.size())
        System.out.println("Index is larger then the date size");
    else {
        if (numberToSort <= 16)
            insertionSort(data, firstIndex, numberToSort);
        else {
            int idx = partition(data, firstIndex, numberToSort);
            int leftSeg = idx - firstIndex;
            int rightSeg = numberToSort - leftSeg - 1;

            quickSort(data, firstIndex, leftSeg);
            quickSort(data, idx + 1, rightSeg); // This is where I get an error
        }
    }
}

@Override
public int partition(ArrayList<String> data, int firstIndex,
        int numberToPartition) {
    String pivot = data.get(firstIndex);
    int TooBigNdx = firstIndex + 1;
    int TooSmallNdx = firstIndex + numberToPartition - 1;

    while (TooBigNdx < TooSmallNdx) {
        while (TooBigNdx < TooSmallNdx
                && data.get(TooBigNdx).compareTo(pivot) <= 0)
            TooBigNdx++;
        while (TooSmallNdx > firstIndex
                && data.get(TooSmallNdx).compareTo(pivot) > 0)
            TooSmallNdx--;
        if (TooBigNdx < TooSmallNdx)
            Collections.swap(data, TooBigNdx, TooSmallNdx);
    }
    if (pivot.compareTo(data.get(TooSmallNdx)) >= 0) {
        Collections.swap(data, firstIndex, TooSmallNdx);
        return TooSmallNdx;
    }
    return firstIndex;
}

每次我运行时都会传递未排序的数组,它运行正常。然而,我的测试人员给了我一个AssertionError。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我尝试了这个例子,通过一些小的代码更改使其易于运行。我在不同的排序数组中尝试作为输入,我没有看到任何太明显的东西。你输入的输入失败了吗?

online compiler IDE for java中的代码 您可以尝试修改输入以查看它失败的位置吗?