二叉堆实现

/*************************************
 * 	BinaryHeap 二叉堆(最小二叉堆 + 最大二叉堆)
 * 	1、Push
 *  2、Pop
 *  3、MinComp
 *  4、MaxComp
 *  5、Clear
 *  6、IsEmpty
 *  7、HeapSize
 * 
 * 	二叉堆:快速排序方式,减少了排序时间复杂度
 */

using UnityEngine;
using System.Collections;

public class BinaryHeap 
{
	public const int MAX_SIZE = 512;
	public int HeapSize{get; private set;}

	private int[] _HeapArray;

	public BinaryHeap()
	{
		Clear();
		_HeapArray = new int[MAX_SIZE];
	}

	public void Clear()
	{
		HeapSize = 0;
	}

	public bool IsEmpty{get{return HeapSize == 0;}}

	private bool MinComp(int x, int y)
	{
		return x < y;
	}

	private bool MaxComp(int x, int y)
	{
		return x > y;
	}

	// 添加新元素,采用冒泡法
	public void Push(int x)
	{
		//首先将 元素放到列表最后面
		HeapSize++;
		_HeapArray[HeapSize] = x;

		// 递归的和其父节点比较,如果,小于父节点就和父节点交换,直至大于等于父节点的值
		int i = 0;
		for(i = HeapSize; i > 0; i = i/ 2)
		{
			int parentIndex = i/2;
			if(parentIndex <= 0)
			{
				break;
			}

			if(MinComp(x, _HeapArray[parentIndex]))
			{
				_HeapArray[i] = _HeapArray[parentIndex];
			}
			else
			{
				break;
			}
		}

		_HeapArray[i] = x;
	}

	// 删除元素,采用向下沉的方式
	public int Pop()
	{
		if(IsEmpty)
		{
			return -1;
		}

		// 取出第一个元素
		int popNum = _HeapArray[1];
		if(HeapSize == 1)
		{
			HeapSize--;
			return popNum;
		}

		// 取出最后一个元素
		int lastNum = _HeapArray[HeapSize];
		HeapSize--;

		// 采用向下沉的方式向下沉
		int i = 1;
		for(; i <= HeapSize;)
		{
			// 如果两个子节点存在,就挑选其中较小的值作为父节点的值
			if((2 * i + 1) <= HeapSize)
			{
				int index = MinComp(_HeapArray[ 2* i], _HeapArray[2 * i + 1])? (2 * i): (2 * i + 1);
				if(MinComp(_HeapArray[index], lastNum))
				{
					_HeapArray[i] = _HeapArray[index];
					i = index;
				}
				else
				{
					break;
				}
			}
			else if((2 * i) <= HeapSize && MinComp(_HeapArray[2 * i], lastNum))
			{
				_HeapArray[i] = _HeapArray[ 2 * i];
				i = 2 * i;
			}
			else
				break;
		}

		_HeapArray[i] = lastNum;

		return popNum;
	}

}

展开阅读全文

没有更多推荐了,返回首页