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. 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.