数据结构和算法之最大堆

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MaxHeap
{

    public class MaxHeap<T>
    {
        private IComparer<T> mComparer;
        private List<T> mItems;

        private int mCount;

        public MaxHeap()
        {
            mComparer = Comparer<T>.Default;
            mItems = new List<T>();
            mItems.Add(default(T));
            mCount = 0;
        }
        public MaxHeap(IComparer<T> comparer)
        {
            mComparer = comparer;
            mItems = new List<T>();
            mItems.Add(default(T));
            mCount = 0;
        }


        public void Insert(T n)
        {
            mCount++;
            mItems.Add(n);
            ShiftUp(mCount);
        }

        public T ExtractMax()
        {
            T ret = mItems[1];
            Swap(1, mCount);
            mCount--;

            ShiftDown(1);
            mItems.Remove(ret);
            return ret;
        }

        public bool IsEmpty()
        {
            return mCount == 0;
        }

        private void ShiftDown(int n)
        {
            //是否有孩子节点
            while(n*2<=mCount)
            {
                int j = n * 2;
                if(j+1<=mCount && mComparer.Compare(mItems[j + 1],mItems[j])>0)
                {
                    j++;//最大的节点
                }
                if(mComparer.Compare(mItems[n],mItems[j])>0)
                {
                    break;
                }
                Swap(n, j);
                n = j;
            }
        }

        private void ShiftUp(int n)
        {
            while (n > 1 && mComparer.Compare(mItems[n], mItems[n / 2]) > 0)
            {
                Swap(n, n / 2);
                n = n / 2;
            }
        }

        private void Swap(int i,int j)
        {
            T tmpValue = mItems[i];
            mItems[i] = mItems[j];
            mItems[j] = tmpValue;
        }




    }
}
// See https://aka.ms/new-console-template for more information
namespace MaxHeap
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            MaxHeap<int> maxHeap = new MaxHeap<int>();
            for (int i = 0; i < 10; i++)
            {
                maxHeap.Insert(i);
            }
            maxHeap.Insert(11);
            while(maxHeap.IsEmpty() == false)
            {
                Console.WriteLine(maxHeap.ExtractMax());
            }
            Console.ReadKey();

        }
    }
}

 

posted @ 2022-01-12 15:31  围墙外的世界  阅读(34)  评论(0编辑  收藏  举报