[英]Counting data comparisons for Java quick sort
我正在尝试计算这种快速排序算法中的数据比较次数,但是由于我的预期输出远远低于当前的输出,因此肯定会增加太多。 在这里,我增加了分区的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会与“可比”绑定,那么您应该避免强制转换
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.