美文网首页
MinHeap(未完待续)

MinHeap(未完待续)

作者: 饭板板 | 来源:发表于2020-11-24 06:48 被阅读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;
}

相关文章

网友评论

      本文标题:MinHeap(未完待续)

      本文链接:https://www.haomeiwen.com/subject/ikgbiktx.html