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

Java快速排序的计数数据比较,java,sorting,Java,Sorting,我试图在这个快速排序算法中计算数据比较的数量,但肯定是增加得太频繁了,因为我的预期输出比我目前得到的要低得多。在这里,我增加了分区的for循环,也增加了每次调用recQuickSort的次数。我错过了什么 private void swap(T[] list, int first, int second) { T temp; temp = list[first]; list[first] = list[second]; list[second] = tem

我试图在这个快速排序算法中计算数据比较的数量,但肯定是增加得太频繁了,因为我的预期输出比我目前得到的要低得多。在这里,我增加了分区的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);

    }
}

从第一眼看,我看不出你会在哪里计算额外的比较。不过,进行此类计数的最简单方法是创建一个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一定会与您的T相当,那么请避免强制转换

好的,我最初尝试从这个线程中采用类似的想法:stackoverflow.com/questions/8292615/…但是,我是Java初学者,在知道如何调用compareInt方法时遇到了问题。你说的“如果你的T是可比的,你可以避免强制转换”是什么意思?我的意思是,我假设这些函数是一个泛型类的一部分,其中泛型参数是T,如果像MyClass,但如果你的类是MyClass,那么你就不需要强制转换了。我添加了一个应该有帮助的示例,尽管我无法测试它。它也不是线程安全的,但是在这种情况下你不应该担心。如果我没有弄错的话,我的答案就在这个类似的线程中: