Обмен свопами и сравнения. Как передать их через две функции
Я пытаюсь подсчитать перестановки и сравнения алгоритма сортировки кучи в C++. До сих пор я написал основную функцию, а также два метода (оба для алгоритма сортировки кучи).
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;
}
Я знаю, что делаю какую-то логическую ошибку, потому что мне очень непонятно передавать переменные через параметры и затем вызывать эти функции с рекурсией.
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);
}
}
Я уверен, что ошибка связана с параметром, который передается по ссылке. Может ли кто-нибудь исправить меня, пожалуйста. Я застрял с этой проблемой. Или, может быть, есть лучший способ подсчета свопов и сравнений?
Если я запускаю это, я получаю ответ:сравнения: 12 обменов: 16
1 ответ
Sorted array is 13, 12, 11, 5, 7, 6, comparisons: 12 swaps: 16
У вас ошибка в heapSort
которые приводят к неправильному результату сортировки. Это также вызывает увеличение количества сравнений и свопов при неудачной попытке успешной сортировки. + Изменить n
в i
во втором звонке 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`
}
}
Результат:
Sorted array is 5, 6, 7, 11, 12, 13, comparisons: 7 swaps: 11