Проблемы с пониманием того, куда поместить счетчики обменов / сравнений в heapsort
Heapsort должен быть таким, чтобы BuildHeap был O(n), а Heapify O(logN), верно? Общая эффективность O(NLogN)?
Но независимо от того, где я разместил свои счетчики, для массива из 2000 элементов я получаю около 35 000-50 000 сравнений + обменов.
Мой код, я вызываю buildheap, а затем запускаю heapSort со встроенным массивом (я получаю около 37 000 сравнений и 20000 обменов):
public class Sort {
static int exchanges = 0;
static int comparisons = 0;
public static void heapSort(int[] array)
{
int size = 2000;
for (int i = 2000; i >= 1; i--)
{
exchanges++;
int temp = array[0];
array[0] = array[i-1];
array[i-1] = temp;
size--;
heapify(array, 0, size);
}
System.out.println("Number of exchanges is: " + exchanges);
System.out.println("Number of comparisons is: " + comparisons);
}
public static int[] buildHeap(int[] array)
{
int N = 2000; //size of array
for (int index = (N/2); index >= 0; index--)
{
heapify(array, index, N);
}
return array;
}
public static void heapify(int[] array, int currentIndex, int N)
{
int leftChild = (2*currentIndex) + 1;
int rightChild = (2*currentIndex)+ 2;
int largest = currentIndex; //just so it's assigned a value at first
if (leftChild <= N-1)
{
comparisons++;
if ((array[leftChild]) > (array[currentIndex]))
{
largest = leftChild;
}
}
else
{
largest = currentIndex;
}
if (rightChild <= N-1)
{
comparisons++;
if ((array[rightChild]) > (array[largest]))
{
largest = rightChild;
}
}
if (largest != currentIndex)
{
exchanges++;
int temp = array[currentIndex];
array[currentIndex] = array[largest];
array[largest] = temp;
heapify(array, largest, N);
}
}
}