MinHeap(未完待续)
2020-11-24 本文已影响0人
饭板板
private void BuildHeap(int[] arr)
{
for (int i = (arr.Length - 2) / 2; i >= 0; i--)
{
DownAdjust(arr, i);
}
}
private void UpAdjust(int[] arr)
{
int childIndex = arr.Length - 1;
int parentIndex = (childIndex - 1) / 2;
int temp = arr[childIndex];
// 注意条件
while (childIndex > 0)
{
if (temp < arr[parentIndex])
{
arr[childIndex] = arr[parentIndex];
childIndex = parentIndex;
parentIndex = (childIndex - 1) / 2;
}
else
{
break;
}
}
arr[childIndex] = temp;
}
private void DownAdjust(int[] arr, int parentIndex)
{
int childIndex = parentIndex * 2 + 1;
int temp = arr[parentIndex];
while (childIndex < arr.Length)
{
if (childIndex < arr.Length - 1 && arr[childIndex] > arr[childIndex + 1])
{
childIndex++;
}
if (temp > arr[childIndex])
{
arr[parentIndex] = arr[childIndex];
parentIndex = childIndex;
childIndex = parentIndex * 2 + 1;
}
else
{
break;
}
}
arr[parentIndex] = temp;
}