I'm trying to count swaps and comparisons of Heap Sort algorithm in c++. So far I have written main function and also two methods(both for heap sort algorithm).
int main()
{
int countComp = 0, countSwap = 0;
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n, countComp, countSwap);
cout << "Sorted array is \n";
printArray(arr, n);
cout << "comparisons: " << countComp << " swaps: " << countSwap << endl;
}
I know I'm making somekind of logical mistake because it is very confusing to me to pass variables through parameters and then call those functions with recursion.
void heapify(int arr[], int n, int i, int& countComparisons, int& countSwaps)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
{
countComparisons++;
largest = l;
}
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
{
countComparisons++;
largest = r;
}
// If largest is not root
if (largest != i)
{
countSwaps++;
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest, countComparisons, countSwaps);
}
}
// main function to do heap sort
void heapSort(int arr[], int n, int& countComparisons, int& countSwaps)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i, countComparisons, countSwaps);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
countSwaps++;
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, n, 0, countComparisons, countSwaps);
}
}
I'm pretty sure mistake is related with parameter which is being passed by reference. Could someone correct me please. I'm stuck with this problem. Or maybe there is a better way to count swaps and comparisons?
If I run this, I get answer : comparisons: 12 swaps: 16
Sorted array is 13, 12, 11, 5, 7, 6, comparisons: 12 swaps: 16
You have an error in heapSort
which lead to the wrong sort result. It also causes increased number of comparisons and swaps in a failed attempt to sort successfully. Change n
to i
in the second call to heapify
void heapSort(int arr[], int n, int& countComparisons, int& countSwaps)
{
for(int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i, countComparisons, countSwaps);
for(int i = n - 1; i >= 0; i--)
{
countSwaps++;
swap(arr[0], arr[i]);
//heapify(arr, n, 0, countComparisons, countSwaps);
heapify(arr, i, 0, countComparisons, countSwaps); //<=== changed `n` to `i`
}
}
Result:
Sorted array is 5, 6, 7, 11, 12, 13, comparisons: 7 swaps: 11