I have a heapsort algorithm.
private int heapSize;
private void BuildHeap(int[] arr)
{
heapSize = arr.Length - 1;
for (int i = heapSize / 2; i >= 0; i--)
{
Heapify(arr, i);
}
}
private void Swap(int[] arr, int x, int y)//function to swap elements
{
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
private void Heapify(int[] arr, int index)
{
int left = 2 * index + 1;
int right = 2 * index + 2;
int largest = index;
if (left <= heapSize && arr[left] > arr[index])
{
largest = left;
}
if (right <= heapSize && arr[right] > arr[largest])
{
largest = right;
}
if (largest != index)
{
Swap(arr, index, largest);
Heapify(arr, largest);
}
}
public int PerformHeapSortTest(int[] arr)
{
int counter = 0;
BuildHeap(arr);
for (int i = arr.Length - 1; i >= 0; i--)
{
Swap(arr, 0, i);
heapSize--;
Heapify(arr, 0);
}
DisplayArray(arr);
}
Private void DisplayArray(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{Console.Write("{0}\n", arr[i])}
}
I want to count the comparisons and don't understand how to implement this using this heap sort algorithm which is in a separate class which I call from the main. I have looked around online and can't find anything. Could some one show me how to implement comparisons to this algorithm?
You need to implement your comparisons using Compare method instead of using operators. Please see full answer here (answer post): how to count heapsort key comparisons