计算Java快速排序的数据比较

时间:2014-05-05 19:27:19

标签: java sorting

我正在尝试计算这种快速排序算法中的数据比较次数,但由于我的预期输出远低于我目前的输出,因此肯定会增加。在这里,我在分区的for循环中以及每次调用recQuickSort时都会增加。我错过了什么?

private void swap(T[] list, int first, int second)
{
     T temp;
     temp = list[first];
     list[first] = list[second];
     list[second] = temp;
     swapsNo++;
}


public void quickSort(T[] list, int length)
{
    recQuickSort(list, 0, length - 1);
}


private int partition(T[] list, int first, int last)
{
    T pivot;

    int smallIndex;

    swap(list, first, (first + last) / 2);

    pivot = list[first];
    smallIndex = first;


    for (int index = first + 1; index <= last; index++)
    {
        Comparable<T> compElem = (Comparable<T>) list[index];
        //Trying to increment comparisons for every time element compared to pivot
        compsNo++;
        if (compElem.compareTo(pivot) < 0)
        {
            smallIndex++;
            swap(list, smallIndex, index);

        }
    }

    swap(list, first, smallIndex);

    return smallIndex;
}



private void recQuickSort(T[] list, int first, int last)
{
    //Trying to increment comparisons every time, as first and last are compared
    compsNo++;
    if (first < last)
    {
        int pivotLocation = partition(list, first, last);
        recQuickSort(list, first, pivotLocation - 1);
        recQuickSort(list, pivotLocation + 1, last);

    }
}

1 个答案:

答案 0 :(得分:0)

从它的第一眼看,我看不出你在哪里计算额外的比较。执行这些类型计数的最简单方法是创建一个CountingComparator类,在每次比较时递增。

class CountingComparator<T extends Comparable<T>> extends Comparator<T> {

      private int count = 0;
      public int compare(T o1, T o2) {
        ++count;
        return o1.compareTo(o2);
      }

      public int getCount() { return count; }
}

此外,如果你的T将被绑定为Comparable,你就会避免演员阵容