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);
}
}
}