我的堆排序实现有一个小问题。基本上,我实现了它,它基本上适用于具有6个或更少元素的数组。但由于某种原因,任何大于6个元素的东西,以及排序都是错误的。
例如:
排序{10,64,7,99,32,18}给出了这个:7,10,18,32,64,99
排序{10,64,7,99,32,18,2,48}给出:2,7,10,32, 18 ,48, 64,99
我的实施如下。随着阵列的大小变大,排序在某种意义上变得更加混乱并且输出不正确。我该如何解决这个问题?
class Program
{
static void Main(string[] args)
{
int[] arr = { 10, 64, 7, 99, 32, 18};
HeapSort hs = new HeapSort();
hs.PerformHeapSort(arr);
Console.ReadLine();
}
}
class HeapSort
{
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;
int right = 2 * index + 1;
int largest;
if (left <= heapSize && arr[left] > arr[index])
{
largest = left;
}
else
{
largest = index;
}
if (right <= heapSize && arr[right] > arr[largest])
{
largest = right;
}
else
{
largest = index;
}
if (largest != index)
{
Swap(arr, index, largest);
Heapify(arr, largest);
}
}
public void PerformHeapSort(int[] arr)
{
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}]", arr[i]); }
}
}
答案 0 :(得分:3)
错误包含在函数Heapify
中。
功能的更正版本:
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);
}
}