简体   繁体   English

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

[英]Counting data comparisons for Java quick sort

I'm trying to count the number of data comparisons in this quick sort algorithm, but am surely incrementing too often as my expected output is much lower than what I am currently getting. 我正在尝试计算这种快速排序算法中的数据比较次数,但是由于我的预期输出远远低于当前的输出,因此肯定会增加太多。 Here, i've incremented in partition's for loop and also every time recQuickSort is called. 在这里,我增加了分区的for循环,并且每次调用recQuickSort时都增加了。 What am I missing? 我想念什么?

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);

    }
}

From the first look of it i dont see where you would be counting extra comparisons. 从它的第一眼看,我看不到您会在哪里计算额外的比较。 The easiest way to do these type of counting though is to create a CountingComparator class that increments on every compare. 但是,执行这些类型的计数的最简单方法是创建一个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; }
}

Also if your T would be bound to Comparable you coupd avoid the casts 另外,如果您的T会与“可比”绑定,那么您应该避免强制转换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM